home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2009 March / ME_03_2009.iso / Software / Internet / Firefox 3.0.8.dmg / Firefox.app / Contents / MacOS / components / nsExtensionManager.js < prev    next >
Encoding:
Text File  |  2009-03-26  |  321.1 KB  |  8,702 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3. //@line 44 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  4. */
  5.  
  6. //
  7. // TODO:
  8. // - better logging
  9. //
  10.  
  11. const Cc = Components.classes;
  12. const Ci = Components.interfaces;
  13. const Cr = Components.results;
  14.  
  15. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  16.  
  17. const PREF_EM_CHECK_COMPATIBILITY     = "extensions.checkCompatibility";
  18. const PREF_EM_CHECK_UPDATE_SECURITY   = "extensions.checkUpdateSecurity";
  19. const PREF_EM_LAST_APP_VERSION        = "extensions.lastAppVersion";
  20. const PREF_EM_ENABLED_ITEMS           = "extensions.enabledItems";
  21. const PREF_UPDATE_COUNT               = "extensions.update.count";
  22. const PREF_UPDATE_DEFAULT_URL         = "extensions.update.url";
  23. const PREF_EM_NEW_ADDONS_LIST         = "extensions.newAddons";
  24. const PREF_EM_IGNOREMTIMECHANGES      = "extensions.ignoreMTimeChanges";
  25. const PREF_EM_DISABLEDOBSOLETE        = "extensions.disabledObsolete";
  26. const PREF_EM_EXTENSION_FORMAT        = "extensions.%UUID%.";
  27. const PREF_EM_ITEM_UPDATE_ENABLED     = "extensions.%UUID%.update.enabled";
  28. const PREF_EM_UPDATE_ENABLED          = "extensions.update.enabled";
  29. const PREF_EM_ITEM_UPDATE_URL         = "extensions.%UUID%.update.url";
  30. const PREF_EM_DSS_ENABLED             = "extensions.dss.enabled";
  31. const PREF_DSS_SWITCHPENDING          = "extensions.dss.switchPending";
  32. const PREF_DSS_SKIN_TO_SELECT         = "extensions.lastSelectedSkin";
  33. const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
  34. const PREF_EM_LOGGING_ENABLED         = "extensions.logging.enabled";
  35. const PREF_EM_UPDATE_INTERVAL         = "extensions.update.interval";
  36. const PREF_UPDATE_NOTIFYUSER          = "extensions.update.notifyUser";
  37. const PREF_MATCH_OS_LOCALE            = "intl.locale.matchOS";
  38. const PREF_SELECTED_LOCALE            = "general.useragent.locale";
  39.  
  40. const DIR_EXTENSIONS                  = "extensions";
  41. const DIR_CHROME                      = "chrome";
  42. const DIR_STAGE                       = "staged-xpis";
  43. const FILE_EXTENSIONS                 = "extensions.rdf";
  44. const FILE_EXTENSION_MANIFEST         = "extensions.ini";
  45. const FILE_EXTENSIONS_STARTUP_CACHE   = "extensions.cache";
  46. const FILE_EXTENSIONS_LOG             = "extensions.log";
  47. const FILE_AUTOREG                    = ".autoreg";
  48. const FILE_INSTALL_MANIFEST           = "install.rdf";
  49. const FILE_CONTENTS_MANIFEST          = "contents.rdf";
  50. const FILE_CHROME_MANIFEST            = "chrome.manifest";
  51.  
  52. const UNKNOWN_XPCOM_ABI               = "unknownABI";
  53.  
  54. const FILE_DEFAULT_THEME_JAR          = "classic.jar";
  55. const TOOLKIT_ID                      = "toolkit@mozilla.org"
  56.  
  57. const KEY_PROFILEDIR                  = "ProfD";
  58. const KEY_PROFILEDS                   = "ProfDS";
  59. const KEY_APPDIR                      = "XCurProcD";
  60. const KEY_TEMPDIR                     = "TmpD";
  61.  
  62. const EM_ACTION_REQUESTED_TOPIC       = "em-action-requested";
  63. const EM_ITEM_INSTALLED               = "item-installed";
  64. const EM_ITEM_UPGRADED                = "item-upgraded";
  65. const EM_ITEM_UNINSTALLED             = "item-uninstalled";
  66. const EM_ITEM_ENABLED                 = "item-enabled";
  67. const EM_ITEM_DISABLED                = "item-disabled";
  68. const EM_ITEM_CANCEL                  = "item-cancel-action";
  69.  
  70. const OP_NONE                         = "";
  71. const OP_NEEDS_INSTALL                = "needs-install";
  72. const OP_NEEDS_UPGRADE                = "needs-upgrade";
  73. const OP_NEEDS_UNINSTALL              = "needs-uninstall";
  74. const OP_NEEDS_ENABLE                 = "needs-enable";
  75. const OP_NEEDS_DISABLE                = "needs-disable";
  76.  
  77. const KEY_APP_PROFILE                 = "app-profile";
  78. const KEY_APP_GLOBAL                  = "app-global";
  79. const KEY_APP_SYSTEM_LOCAL            = "app-system-local";
  80. const KEY_APP_SYSTEM_SHARE            = "app-system-share";
  81. const KEY_APP_SYSTEM_USER             = "app-system-user";
  82.  
  83. const CATEGORY_INSTALL_LOCATIONS      = "extension-install-locations";
  84. const CATEGORY_UPDATE_PARAMS          = "extension-update-params";
  85.  
  86. const PREFIX_NS_EM                    = "http://www.mozilla.org/2004/em-rdf#";
  87. const PREFIX_NS_CHROME                = "http://www.mozilla.org/rdf/chrome#";
  88. const PREFIX_ITEM_URI                 = "urn:mozilla:item:";
  89. const PREFIX_EXTENSION                = "urn:mozilla:extension:";
  90. const PREFIX_THEME                    = "urn:mozilla:theme:";
  91. const RDFURI_INSTALL_MANIFEST_ROOT    = "urn:mozilla:install-manifest";
  92. const RDFURI_ITEM_ROOT                = "urn:mozilla:item:root"
  93. const RDFURI_DEFAULT_THEME            = "urn:mozilla:item:{972ce4c6-7e08-4474-a285-3208198ce6fd}";
  94. const XMLURI_PARSE_ERROR              = "http://www.mozilla.org/newlayout/xml/parsererror.xml"
  95.  
  96. const URI_GENERIC_ICON_XPINSTALL      = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  97. const URI_GENERIC_ICON_THEME          = "chrome://mozapps/skin/extensions/themeGeneric.png";
  98. const URI_XPINSTALL_CONFIRM_DIALOG    = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
  99. const URI_EXTENSIONS_PROPERTIES       = "chrome://mozapps/locale/extensions/extensions.properties";
  100. const URI_BRAND_PROPERTIES            = "chrome://branding/locale/brand.properties";
  101. const URI_DOWNLOADS_PROPERTIES        = "chrome://mozapps/locale/downloads/downloads.properties";
  102. const URI_EXTENSION_UPDATE_DIALOG     = "chrome://mozapps/content/extensions/update.xul";
  103. const URI_EXTENSION_LIST_DIALOG       = "chrome://mozapps/content/extensions/list.xul";
  104.  
  105. const INSTALLERROR_SUCCESS               = 0;
  106. const INSTALLERROR_INVALID_VERSION       = -1;
  107. const INSTALLERROR_INVALID_GUID          = -2;
  108. const INSTALLERROR_INCOMPATIBLE_VERSION  = -3;
  109. const INSTALLERROR_PHONED_HOME           = -4;
  110. const INSTALLERROR_INCOMPATIBLE_PLATFORM = -5;
  111. const INSTALLERROR_BLOCKLISTED           = -6;
  112. const INSTALLERROR_INSECURE_UPDATE       = -7;
  113. const INSTALLERROR_INVALID_MANIFEST      = -8;
  114. const INSTALLERROR_RESTRICTED            = -9;
  115.  
  116. const MODE_RDONLY   = 0x01;
  117. const MODE_WRONLY   = 0x02;
  118. const MODE_CREATE   = 0x08;
  119. const MODE_APPEND   = 0x10;
  120. const MODE_TRUNCATE = 0x20;
  121.  
  122. const PERMS_FILE      = 0644;
  123. const PERMS_DIRECTORY = 0755;
  124.  
  125. var gApp  = null;
  126. var gPref = null;
  127. var gRDF  = null;
  128. var gOS   = null;
  129. var gBlocklist            = null;
  130. var gXPCOMABI             = null;
  131. var gOSTarget             = null;
  132. var gConsole              = null;
  133. var gInstallManifestRoot  = null;
  134. var gVersionChecker       = null;
  135. var gLoggingEnabled       = null;
  136. var gCheckCompatibility   = true;
  137. var gCheckUpdateSecurity  = true;
  138. var gLocale               = "en-US";
  139. var gFirstRun             = false;
  140. var gAllowFlush           = true;
  141. var gDSNeedsFlush         = false;
  142. var gManifestNeedsFlush   = false;
  143.  
  144. /**
  145.  * Valid GUIDs fit this pattern.
  146.  */
  147. var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
  148.  
  149. // shared code for suppressing bad cert dialogs
  150. //@line 40 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/shared/src/badCertHandler.js"
  151.  
  152. /**
  153.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  154.  */
  155. function checkCert(channel) {
  156.   if (!channel.originalURI.schemeIs("https"))  // bypass
  157.     return;
  158.  
  159.   const Ci = Components.interfaces;  
  160.   var cert =
  161.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  162.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  163.  
  164.   var issuer = cert.issuer;
  165.   while (issuer && !cert.equals(issuer)) {
  166.     cert = issuer;
  167.     issuer = cert.issuer;
  168.   }
  169.  
  170.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  171.     throw "cert issuer is not built-in";
  172. }
  173.  
  174. /**
  175.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  176.  * security dialogs from being shown to the user.  It is better to simply fail
  177.  * if the certificate is bad. See bug 304286.
  178.  */
  179. function BadCertHandler() {
  180. }
  181. BadCertHandler.prototype = {
  182.  
  183.   // nsIChannelEventSink
  184.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  185.     // make sure the certificate of the old channel checks out before we follow
  186.     // a redirect from it.  See bug 340198.
  187.     checkCert(oldChannel);
  188.   },
  189.  
  190.   // Suppress any certificate errors
  191.   notifyCertProblem: function(socketInfo, status, targetSite) {
  192.     return true;
  193.   },
  194.  
  195.   // Suppress any ssl errors
  196.   notifySSLError: function(socketInfo, error, targetSite) {
  197.     return true;
  198.   },
  199.  
  200.   // nsIInterfaceRequestor
  201.   getInterface: function(iid) {
  202.     return this.QueryInterface(iid);
  203.   },
  204.  
  205.   // nsISupports
  206.   QueryInterface: function(iid) {
  207.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  208.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  209.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  210.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  211.         !iid.equals(Components.interfaces.nsISupports))
  212.       throw Components.results.NS_ERROR_NO_INTERFACE;
  213.     return this;
  214.   }
  215. };
  216. //@line 191 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  217.  
  218. /**
  219.  * Creates a Version Checker object.
  220.  * @returns A handle to the global Version Checker service.
  221.  */
  222. function getVersionChecker() {
  223.   if (!gVersionChecker) {
  224.     gVersionChecker = Cc["@mozilla.org/xpcom/version-comparator;1"].
  225.                       getService(Ci.nsIVersionComparator);
  226.   }
  227.   return gVersionChecker;
  228. }
  229.  
  230. var BundleManager = {
  231.   /**
  232.   * Creates and returns a String Bundle at the specified URI
  233.   * @param   bundleURI
  234.   *          The URI of the bundle to load
  235.   * @returns A nsIStringBundle which was retrieved.
  236.   */
  237.   getBundle: function(bundleURI) {
  238.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  239.               getService(Ci.nsIStringBundleService);
  240.     return sbs.createBundle(bundleURI);
  241.   },
  242.  
  243.   _appName: "",
  244.  
  245.   /**
  246.    * The Application's display name.
  247.    */
  248.   get appName() {
  249.     if (!this._appName) {
  250.       var brandBundle = this.getBundle(URI_BRAND_PROPERTIES)
  251.       this._appName = brandBundle.GetStringFromName("brandShortName");
  252.     }
  253.     return this._appName;
  254.   }
  255. };
  256.  
  257. ///////////////////////////////////////////////////////////////////////////////
  258. //
  259. // Utility Functions
  260. //
  261. function EM_NS(property) {
  262.   return PREFIX_NS_EM + property;
  263. }
  264.  
  265. function CHROME_NS(property) {
  266.   return PREFIX_NS_CHROME + property;
  267. }
  268.  
  269. function EM_R(property) {
  270.   return gRDF.GetResource(EM_NS(property));
  271. }
  272.  
  273. function EM_L(literal) {
  274.   return gRDF.GetLiteral(literal);
  275. }
  276.  
  277. function EM_I(integer) {
  278.   return gRDF.GetIntLiteral(integer);
  279. }
  280.  
  281. function EM_D(integer) {
  282.   return gRDF.GetDateLiteral(integer);
  283. }
  284.  
  285. /**
  286.  * Gets a preference value, handling the case where there is no default.
  287.  * @param   func
  288.  *          The name of the preference function to call, on nsIPrefBranch
  289.  * @param   preference
  290.  *          The name of the preference
  291.  * @param   defaultValue
  292.  *          The default value to return in the event the preference has
  293.  *          no setting
  294.  * @returns The value of the preference, or undefined if there was no
  295.  *          user or default value.
  296.  */
  297. function getPref(func, preference, defaultValue) {
  298.   try {
  299.     return gPref[func](preference);
  300.   }
  301.   catch (e) {
  302.   }
  303.   return defaultValue;
  304. }
  305.  
  306. /**
  307.  * Initializes a RDF Container at a URI in a datasource.
  308.  * @param   datasource
  309.  *          The datasource the container is in
  310.  * @param   root
  311.  *          The RDF Resource which is the root of the container.
  312.  * @returns The nsIRDFContainer, initialized at the root.
  313.  */
  314. function getContainer(datasource, root) {
  315.   var ctr = Cc["@mozilla.org/rdf/container;1"].
  316.             createInstance(Ci.nsIRDFContainer);
  317.   ctr.Init(datasource, root);
  318.   return ctr;
  319. }
  320.  
  321. /**
  322.  * Gets a RDF Resource for item with the given ID
  323.  * @param   id
  324.  *          The GUID of the item to construct a RDF resource to the
  325.  *          active item for
  326.  * @returns The RDF Resource to the Active item.
  327.  */
  328. function getResourceForID(id) {
  329.   return gRDF.GetResource(PREFIX_ITEM_URI + id);
  330. }
  331.  
  332. /**
  333.  * Construct a nsIUpdateItem with the supplied metadata
  334.  * ...
  335.  */
  336. function makeItem(id, version, locationKey, minVersion, maxVersion, name,
  337.                   updateURL, updateHash, iconURL, updateRDF, updateKey, type, 
  338.                   targetAppID) {
  339.   var item = new UpdateItem();
  340.   item.init(id, version, locationKey, minVersion, maxVersion, name,
  341.             updateURL, updateHash, iconURL, updateRDF, updateKey, type,
  342.             targetAppID);
  343.   return item;
  344. }
  345.  
  346. /**
  347.  * Gets the specified directory at the specified hierarchy under a
  348.  * Directory Service key.
  349.  * @param   key
  350.  *          The Directory Service Key to start from
  351.  * @param   pathArray
  352.  *          An array of path components to locate beneath the directory
  353.  *          specified by |key|
  354.  * @return  nsIFile object for the location specified. If the directory
  355.  *          requested does not exist, it is created, along with any
  356.  *          parent directories that need to be created.
  357.  */
  358. function getDir(key, pathArray) {
  359.   return getDirInternal(key, pathArray, true);
  360. }
  361.  
  362. /**
  363.  * Gets the specified directory at the specified hierarchy under a
  364.  * Directory Service key.
  365.  * @param   key
  366.  *          The Directory Service Key to start from
  367.  * @param   pathArray
  368.  *          An array of path components to locate beneath the directory
  369.  *          specified by |key|
  370.  * @return  nsIFile object for the location specified. If the directory
  371.  *          requested does not exist, it is NOT created.
  372.  */
  373. function getDirNoCreate(key, pathArray) {
  374.   return getDirInternal(key, pathArray, false);
  375. }
  376.  
  377. /**
  378.  * Gets the specified directory at the specified hierarchy under a
  379.  * Directory Service key.
  380.  * @param   key
  381.  *          The Directory Service Key to start from
  382.  * @param   pathArray
  383.  *          An array of path components to locate beneath the directory
  384.  *          specified by |key|
  385.  * @param   shouldCreate
  386.  *          true if the directory hierarchy specified in |pathArray|
  387.  *          should be created if it does not exist,
  388.  *          false otherwise.
  389.  * @return  nsIFile object for the location specified.
  390.  */
  391. function getDirInternal(key, pathArray, shouldCreate) {
  392.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  393.                     getService(Ci.nsIProperties);
  394.   var dir = fileLocator.get(key, Ci.nsILocalFile);
  395.   for (var i = 0; i < pathArray.length; ++i) {
  396.     dir.append(pathArray[i]);
  397.     if (shouldCreate && !dir.exists())
  398.       dir.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  399.   }
  400.   dir.followLinks = false;
  401.   return dir;
  402. }
  403.  
  404. /**
  405.  * Gets the file at the specified hierarchy under a Directory Service key.
  406.  * @param   key
  407.  *          The Directory Service Key to start from
  408.  * @param   pathArray
  409.  *          An array of path components to locate beneath the directory
  410.  *          specified by |key|. The last item in this array must be the
  411.  *          leaf name of a file.
  412.  * @return  nsIFile object for the file specified. The file is NOT created
  413.  *          if it does not exist, however all required directories along
  414.  *          the way are.
  415.  */
  416. function getFile(key, pathArray) {
  417.   var file = getDir(key, pathArray.slice(0, -1));
  418.   file.append(pathArray[pathArray.length - 1]);
  419.   return file;
  420. }
  421.  
  422. /**
  423.  * Gets the descriptor of a directory as a relative path to common base
  424.  * directories (profile, user home, app install dir, etc).
  425.  *
  426.  * @param   itemLocation
  427.  *          The nsILocalFile representing the item's directory.
  428.  * @param   installLocation the nsIInstallLocation for this item
  429.  */
  430. function getDescriptorFromFile(itemLocation, installLocation) {
  431.   var baseDir = installLocation.location;
  432.  
  433.   if (baseDir && baseDir.contains(itemLocation, true)) {
  434.     return "rel%" + itemLocation.getRelativeDescriptor(baseDir);
  435.   }
  436.  
  437.   return "abs%" + itemLocation.persistentDescriptor;
  438. }
  439.  
  440. function getAbsoluteDescriptor(itemLocation) {
  441.   return itemLocation.persistentDescriptor;
  442. }
  443.  
  444. /**
  445.  * Initializes a Local File object based on a descriptor
  446.  * provided by "getDescriptorFromFile".
  447.  *
  448.  * @param   descriptor
  449.  *          The descriptor that locates the directory
  450.  * @param   installLocation
  451.  *          The nsIInstallLocation object for this item.
  452.  * @returns The nsILocalFile object representing the location of the item
  453.  */
  454. function getFileFromDescriptor(descriptor, installLocation) {
  455.   var location = Cc["@mozilla.org/file/local;1"].
  456.                  createInstance(Ci.nsILocalFile);
  457.  
  458.   var m = descriptor.match(/^(abs|rel)\%(.*)$/);
  459.   if (!m)
  460.     throw Cr.NS_ERROR_INVALID_ARG;
  461.  
  462.   if (m[1] == "rel") {
  463.     location.setRelativeDescriptor(installLocation.location, m[2]);
  464.   }
  465.   else {
  466.     location.persistentDescriptor = m[2];
  467.   }
  468.  
  469.   return location;
  470. }
  471.  
  472. /**
  473.  * Determines if a file is an item package - either a XPI or a JAR file.
  474.  * @param   file
  475.  *          The file to check
  476.  * @returns true if the file is an item package, false otherwise.
  477.  */
  478. function fileIsItemPackage(file) {
  479.   var fileURL = getURIFromFile(file);
  480.   if (fileURL instanceof Ci.nsIURL)
  481.     var extension = fileURL.fileExtension.toLowerCase();
  482.   return extension == "xpi" || extension == "jar";
  483. }
  484.  
  485. /**
  486.  * Opens a safe file output stream for writing.
  487.  * @param   file
  488.  *          The file to write to.
  489.  * @param   modeFlags
  490.  *          (optional) File open flags. Can be undefined.
  491.  * @returns nsIFileOutputStream to write to.
  492.  */
  493. function openSafeFileOutputStream(file, modeFlags) {
  494.   var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  495.             createInstance(Ci.nsIFileOutputStream);
  496.   if (modeFlags === undefined)
  497.     modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  498.   if (!file.exists())
  499.     file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  500.   fos.init(file, modeFlags, PERMS_FILE, 0);
  501.   return fos;
  502. }
  503.  
  504. /**
  505.  * Closes a safe file output stream.
  506.  * @param   stream
  507.  *          The stream to close.
  508.  */
  509. function closeSafeFileOutputStream(stream) {
  510.   if (stream instanceof Ci.nsISafeOutputStream)
  511.     stream.finish();
  512.   else
  513.     stream.close();
  514. }
  515.  
  516. /**
  517.  * Deletes a directory and its children. First it tries nsIFile::Remove(true).
  518.  * If that fails it will fall back to recursing, setting the appropriate
  519.  * permissions, and deleting the current entry. This is needed for when we have
  520.  * rights to delete a directory but there are entries that have a read-only
  521.  * attribute (e.g. a copy restore from a read-only CD, etc.)
  522.  * @param   dir
  523.  *          A nsIFile for the directory to be deleted
  524.  */
  525. function removeDirRecursive(dir) {
  526.   try {
  527.     dir.remove(true);
  528.     return;
  529.   }
  530.   catch (e) {
  531.   }
  532.  
  533.   var dirEntries = dir.directoryEntries;
  534.   while (dirEntries.hasMoreElements()) {
  535.     var entry = dirEntries.getNext().QueryInterface(Ci.nsIFile);
  536.  
  537.     if (entry.isDirectory()) {
  538.       removeDirRecursive(entry);
  539.     }
  540.     else {
  541.       entry.permissions = PERMS_FILE;
  542.       entry.remove(false);
  543.     }
  544.   }
  545.   dir.permissions = PERMS_DIRECTORY;
  546.   dir.remove(true);
  547. }
  548.  
  549. /**
  550.  * Logs a string to the error console.
  551.  * @param   string
  552.  *          The string to write to the error console.
  553.  */
  554. function LOG(string) {
  555.   if (gLoggingEnabled) {
  556.     dump("*** " + string + "\n");
  557.     if (gConsole)
  558.       gConsole.logStringMessage(string);
  559.   }
  560. }
  561.  
  562. /**
  563.  * Logs a string to the error console and to a permanent log file. 
  564.  * @param   string
  565.  *          The string to write out.
  566.  */  
  567. function ERROR(string) {
  568.   LOG(string);
  569.   try {
  570.     var tstamp = new Date();
  571.     var logfile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_LOG]);
  572.     var stream = Cc["@mozilla.org/network/file-output-stream;1"].
  573.                  createInstance(Ci.nsIFileOutputStream);
  574.     stream.init(logfile, 0x02 | 0x08 | 0x10, 0666, 0); // write, create, append
  575.     var writer = Cc["@mozilla.org/intl/converter-output-stream;1"].
  576.                  createInstance(Ci.nsIConverterOutputStream);
  577.     writer.init(stream, "UTF-8", 0, 0x0000);
  578.     string = tstamp.toLocaleFormat("%Y-%m-%d %H:%M:%S - ") + string;
  579.     writer.writeString(string + "\n");
  580.     writer.close();
  581.   }
  582.   catch (e) { }
  583. }
  584.  
  585. /**
  586.  * Randomize the specified file name. Used to force RDF to bypass the cache
  587.  * when loading certain types of files.
  588.  * @param   fileName
  589.  *          A file name to randomize, e.g. install.rdf
  590.  * @returns A randomized file name, e.g. install-xyz.rdf
  591.  */
  592. function getRandomFileName(fileName) {
  593.   var extensionDelimiter = fileName.lastIndexOf(".");
  594.   var prefix = fileName.substr(0, extensionDelimiter);
  595.   var suffix = fileName.substr(extensionDelimiter);
  596.  
  597.   var characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  598.   var nameString = prefix + "-";
  599.   for (var i = 0; i < 3; ++i) {
  600.     var index = Math.round((Math.random()) * characters.length);
  601.     nameString += characters.charAt(index);
  602.   }
  603.   return nameString + "." + suffix;
  604. }
  605.  
  606. /**
  607.  * Get the RDF URI prefix of a nsIUpdateItem type. This function should be used
  608.  * ONLY to support Firefox 1.0 Update RDF files! Item URIs in the datasource
  609.  * are NOT prefixed.
  610.  * @param   type
  611.  *          The nsIUpdateItem type to find a RDF URI prefix for
  612.  * @returns The RDF URI prefix.
  613.  */
  614. function getItemPrefix(type) {
  615.   if (type & Ci.nsIUpdateItem.TYPE_EXTENSION)
  616.     return PREFIX_EXTENSION;
  617.   else if (type & Ci.nsIUpdateItem.TYPE_THEME)
  618.     return PREFIX_THEME;
  619.   return PREFIX_ITEM_URI;
  620. }
  621.  
  622. /**
  623.  * Trims a prefix from a string.
  624.  * @param   string
  625.  *          The source string
  626.  * @param   prefix
  627.  *          The prefix to remove.
  628.  * @returns The suffix (string - prefix)
  629.  */
  630. function stripPrefix(string, prefix) {
  631.   return string.substr(prefix.length);
  632. }
  633.  
  634. /**
  635.  * Gets a File URL spec for a nsIFile
  636.  * @param   file
  637.  *          The file to get a file URL spec to
  638.  * @returns The file URL spec to the file
  639.  */
  640. function getURLSpecFromFile(file) {
  641.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  642.                getService(Ci.nsIIOService);
  643.   var fph = ioServ.getProtocolHandler("file")
  644.                   .QueryInterface(Ci.nsIFileProtocolHandler);
  645.   return fph.getURLSpecFromFile(file);
  646. }
  647.  
  648. /**
  649.  * Constructs a URI to a spec.
  650.  * @param   spec
  651.  *          The spec to construct a URI to
  652.  * @returns The nsIURI constructed.
  653.  */
  654. function newURI(spec) {
  655.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  656.                getService(Ci.nsIIOService);
  657.   return ioServ.newURI(spec, null, null);
  658. }
  659.  
  660. /**
  661.  * Constructs a File URI to a nsIFile
  662.  * @param   file
  663.  *          The file to construct a File URI to
  664.  * @returns The file URI to the file
  665.  */
  666. function getURIFromFile(file) {
  667.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  668.                getService(Ci.nsIIOService);
  669.   return ioServ.newFileURI(file);
  670. }
  671.  
  672. /**
  673.  * @returns Whether or not we are currently running in safe mode.
  674.  */
  675. function inSafeMode() {
  676.   return gApp.inSafeMode;
  677. }
  678.  
  679. /**
  680.  * Extract the string value from a RDF Literal or Resource
  681.  * @param   literalOrResource
  682.  *          RDF String Literal or Resource
  683.  * @returns String value of the literal or resource, or undefined if the object
  684.  *          supplied is not a RDF string literal or resource.
  685.  */
  686. function stringData(literalOrResource) {
  687.   if (literalOrResource instanceof Ci.nsIRDFLiteral)
  688.     return literalOrResource.Value;
  689.   if (literalOrResource instanceof Ci.nsIRDFResource)
  690.     return literalOrResource.Value;
  691.   return undefined;
  692. }
  693.  
  694. /**
  695.  * Extract the integer value of a RDF Literal
  696.  * @param   literal
  697.  *          nsIRDFInt literal
  698.  * @return  integer value of the literal
  699.  */
  700. function intData(literal) {
  701.   if (literal instanceof Ci.nsIRDFInt)
  702.     return literal.Value;
  703.   return undefined;
  704. }
  705.  
  706. /**
  707.  * Gets a property from an install manifest.
  708.  * @param   installManifest
  709.  *          An Install Manifest datasource to read from
  710.  * @param   property
  711.  *          The name of a proprety to read (sans EM_NS)
  712.  * @returns The literal value of the property, or undefined if the property has
  713.  *          no value.
  714.  */
  715. function getManifestProperty(installManifest, property) {
  716.   var target = installManifest.GetTarget(gInstallManifestRoot,
  717.                                          gRDF.GetResource(EM_NS(property)), true);
  718.   var val = stringData(target);
  719.   return val === undefined ? intData(target) : val;
  720. }
  721.  
  722. /**
  723.  * Given an Install Manifest Datasource, retrieves the type of item the manifest
  724.  * describes.
  725.  * @param   installManifest
  726.  *          The Install Manifest Datasource.
  727.  * @return  The nsIUpdateItem type of the item described by the manifest
  728.  *          returns TYPE_EXTENSION if attempts to determine the type fail.
  729.  */
  730. function getAddonTypeFromInstallManifest(installManifest) {
  731.   var target = installManifest.GetTarget(gInstallManifestRoot,
  732.                                          gRDF.GetResource(EM_NS("type")), true);
  733.   if (target) {
  734.     var type = stringData(target);
  735.     return type === undefined ? intData(target) : parseInt(type);
  736.   }
  737.  
  738.   // Firefox 1.0 and earlier did not support addon-type annotation on the
  739.   // Install Manifest, so we fall back to a theme-only property to
  740.   // differentiate.
  741.   if (getManifestProperty(installManifest, "internalName") !== undefined)
  742.     return Ci.nsIUpdateItem.TYPE_THEME;
  743.  
  744.   // If no type is provided, default to "Extension"
  745.   return Ci.nsIUpdateItem.TYPE_EXTENSION;
  746. }
  747.  
  748. /**
  749.  * Shows a message about an incompatible Extension/Theme.
  750.  * @param   installData
  751.  *          An Install Data object from |getInstallData|
  752.  */
  753. function showIncompatibleError(installData) {
  754.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  755.   var params = [extensionStrings.GetStringFromName("type-" + installData.type)];
  756.   var title = extensionStrings.formatStringFromName("incompatibleTitle",
  757.                                                     params, params.length);
  758.   params = [installData.name, installData.version, BundleManager.appName,
  759.             gApp.version];
  760.   var message = extensionStrings.formatStringFromName("incompatibleMessage",
  761.                                                       params, params.length);
  762.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  763.            getService(Ci.nsIPromptService);
  764.   ps.alert(null, title, message);
  765. }
  766.  
  767. /**
  768.  * Shows a message.
  769.  * @param   titleKey
  770.  *          String key of the title string in the Extensions localization file.
  771.  * @param   messageKey
  772.  *          String key of the message string in the Extensions localization file.
  773.  * @param   messageParams
  774.  *          Array of strings to be substituted into |messageKey|. Can be null.
  775.  */
  776. function showMessage(titleKey, titleParams, messageKey, messageParams) {
  777.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  778.   if (titleParams && titleParams.length > 0) {
  779.     var title = extensionStrings.formatStringFromName(titleKey, titleParams,
  780.                                                       titleParams.length);
  781.   }
  782.   else
  783.     title = extensionStrings.GetStringFromName(titleKey);
  784.  
  785.   if (messageParams && messageParams.length > 0) {
  786.     var message = extensionStrings.formatStringFromName(messageKey, messageParams,
  787.                                                         messageParams.length);
  788.   }
  789.   else
  790.     message = extensionStrings.GetStringFromName(messageKey);
  791.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  792.            getService(Ci.nsIPromptService);
  793.   ps.alert(null, title, message);
  794. }
  795.  
  796. /**
  797.  * Shows a dialog for blocklisted items.
  798.  * @param   items
  799.  *          An array of nsIUpdateItems.
  800.  * @param   fromInstall
  801.  *          Whether this is called from an install or from the blocklist
  802.  *          background check.
  803.  */
  804. function showBlocklistMessage(items, fromInstall) {
  805.   var win = null;
  806.   var params = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  807.                createInstance(Ci.nsIDialogParamBlock);
  808.   params.SetInt(0, (fromInstall ? 1 : 0));
  809.   params.SetInt(1, items.length);
  810.   params.SetNumberStrings(items.length * 2);
  811.   for (var i = 0; i < items.length; ++i)
  812.     params.SetString(i, items[i].name + " " + items[i].version);
  813.  
  814.   // if this was initiated from an install try to find the appropriate manager
  815.   if (fromInstall) {
  816.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  817.              getService(Ci.nsIWindowMediator);
  818.     win = wm.getMostRecentWindow("Extension:Manager");
  819.   }
  820.   var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  821.            getService(Ci.nsIWindowWatcher);
  822.   ww.openWindow(win, URI_EXTENSION_LIST_DIALOG, "",
  823.                 "chrome,centerscreen,modal,dialog,titlebar", params);
  824. }
  825.  
  826. /**
  827.  * Gets a zip reader for the file specified.
  828.  * @param   zipFile
  829.  *          A ZIP archive to open with a nsIZipReader.
  830.  * @return  A nsIZipReader for the file specified.
  831.  */
  832. function getZipReaderForFile(zipFile) {
  833.   try {
  834.     var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
  835.                     createInstance(Ci.nsIZipReader);
  836.     zipReader.open(zipFile);
  837.   }
  838.   catch (e) {
  839.     zipReader.close();
  840.     throw e;
  841.   }
  842.   return zipReader;
  843. }
  844.  
  845. /**
  846.  * Extract a RDF file from a ZIP archive to a random location in the system
  847.  * temp directory.
  848.  * @param   zipFile
  849.  *          A ZIP archive to read from
  850.  * @param   fileName
  851.  *          The name of the file to read from the zip.
  852.  * @param   suppressErrors
  853.  *          Whether or not to report errors.
  854.  * @return  The file created in the temp directory.
  855.  */
  856. function extractRDFFileToTempDir(zipFile, fileName, suppressErrors) {
  857.   var file = getFile(KEY_TEMPDIR, [getRandomFileName(fileName)]);
  858.   try {
  859.     var zipReader = getZipReaderForFile(zipFile);
  860.     zipReader.extract(fileName, file);
  861.     zipReader.close();
  862.   }
  863.   catch (e) {
  864.     if (!suppressErrors) {
  865.       showMessage("missingFileTitle", [], "missingFileMessage",
  866.                   [BundleManager.appName, fileName]);
  867.       throw e;
  868.     }
  869.   }
  870.   return file;
  871. }
  872.  
  873. /**
  874.  * Gets an Install Manifest datasource from a file.
  875.  * @param   file
  876.  *          The nsIFile that contains the Install Manifest RDF
  877.  * @returns The Install Manifest datasource
  878.  */
  879. function getInstallManifest(file) {
  880.   var uri = getURIFromFile(file);
  881.   try {
  882.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  883.               createInstance(Ci.nsIFileInputStream);
  884.     fis.init(file, -1, -1, false);
  885.     var bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
  886.               createInstance(Ci.nsIBufferedInputStream);
  887.     bis.init(fis, 4096);
  888.     
  889.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  890.                     createInstance(Ci.nsIRDFXMLParser)
  891.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  892.              createInstance(Ci.nsIRDFDataSource);
  893.     var listener = rdfParser.parseAsync(ds, uri);
  894.     var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
  895.                   createInstance(Ci.nsIInputStreamChannel);
  896.     channel.setURI(uri);
  897.     channel.contentStream = bis;
  898.     channel.QueryInterface(Ci.nsIChannel);
  899.     channel.contentType = "text/xml";
  900.   
  901.     listener.onStartRequest(channel, null);
  902.     try {
  903.       var pos = 0;
  904.       var count = bis.available();
  905.       while (count > 0) {
  906.         listener.onDataAvailable(channel, null, bis, pos, count);
  907.         pos += count;
  908.         count = bis.available();
  909.       }
  910.       listener.onStopRequest(channel, null, Components.results.NS_OK);
  911.       bis.close();
  912.       fis.close();
  913.  
  914.       var arcs = ds.ArcLabelsOut(gInstallManifestRoot);
  915.       if (arcs.hasMoreElements())
  916.         return ds;
  917.     }
  918.     catch (e) {
  919.       listener.onStopRequest(channel, null, e.result);
  920.       bis.close();
  921.       fis.close();
  922.     }
  923.   }
  924.   catch (e) { }
  925.  
  926.   var url = uri.QueryInterface(Ci.nsIURL);
  927.   showMessage("malformedTitle", [], "malformedMessage",
  928.               [BundleManager.appName, url.fileName]);
  929.   return null;
  930. }
  931.  
  932. /**
  933.  * Selects the closest matching localized resource in the given RDF resource
  934.  * @param   aDataSource The datasource to look in
  935.  * @param   aResource   The root resource containing the localized sections
  936.  * @returns The nsIRDFResource of the best em:localized section or null
  937.  *          if no valid match was found
  938.  */
  939. function findClosestLocalizedResource(aDataSource, aResource) {
  940.   var localizedProp = EM_R("localized");
  941.   var localeProp = EM_R("locale");
  942.  
  943.   // Holds the best matching localized resource
  944.   var bestmatch = null;
  945.   // The number of locale parts it matched with
  946.   var bestmatchcount = 0;
  947.   // The number of locale parts in the match
  948.   var bestpartcount = 0;
  949.  
  950.   var locales = [gLocale.toLowerCase()];
  951.   /* If the current locale is English then it will find a match if there is
  952.      a valid match for en-US so no point searching that locale too. */
  953.   if (locales[0].substring(0, 3) != "en-")
  954.     locales.push("en-us");
  955.  
  956.   for each (var locale in locales) {
  957.     var lparts = locale.split("-");
  958.     var localizations = aDataSource.GetTargets(aResource, localizedProp, true);
  959.     while (localizations.hasMoreElements()) {
  960.       var localized = localizations.getNext().QueryInterface(Ci.nsIRDFNode);
  961.       var list = aDataSource.GetTargets(localized, localeProp, true);
  962.       while (list.hasMoreElements()) {
  963.         var found = stringData(list.getNext().QueryInterface(Ci.nsIRDFNode));
  964.         if (!found)
  965.           continue;
  966.  
  967.         found = found.toLowerCase();
  968.  
  969.         // Exact match is returned immediately
  970.         if (locale == found)
  971.           return localized;
  972.   
  973.         var fparts = found.split("-");
  974.         /* If we have found a possible match and this one isn't any longer
  975.            then we dont need to check further. */
  976.         if (bestmatch && fparts.length < bestmatchcount)
  977.           continue;
  978.   
  979.         // Count the number of parts that match
  980.         var maxmatchcount = Math.min(fparts.length, lparts.length);
  981.         var matchcount = 0;
  982.         while (matchcount < maxmatchcount &&
  983.                fparts[matchcount] == lparts[matchcount])
  984.           matchcount++;
  985.   
  986.         /* If we matched more than the last best match or matched the same and
  987.            this locale is less specific than the last best match. */
  988.         if (matchcount > bestmatchcount ||
  989.            (matchcount == bestmatchcount && fparts.length < bestpartcount)) {
  990.           bestmatch = localized;
  991.           bestmatchcount = matchcount;
  992.           bestpartcount = fparts.length;
  993.         }
  994.       }
  995.     }
  996.     // If we found a valid match for this locale return it
  997.     if (bestmatch)
  998.       return bestmatch;
  999.   }
  1000.   return null;
  1001. }
  1002.     
  1003. /**
  1004.  * An enumeration of items in a JS array.
  1005.  * @constructor
  1006.  */
  1007. function ArrayEnumerator(aItems) {
  1008.   if (aItems) {
  1009.     for (var i = 0; i < aItems.length; ++i) {
  1010.       if (!aItems[i])
  1011.         aItems.splice(i--, 1);
  1012.     }
  1013.     this._contents = aItems;
  1014.   } else {
  1015.     this._contents = [];
  1016.   }
  1017. }
  1018.  
  1019. ArrayEnumerator.prototype = {
  1020.   _index: 0,
  1021.  
  1022.   hasMoreElements: function () {
  1023.     return this._index < this._contents.length;
  1024.   },
  1025.  
  1026.   getNext: function () {
  1027.     return this._contents[this._index++];
  1028.   }
  1029. };
  1030.  
  1031. /**
  1032.  * An enumeration of files in a JS array.
  1033.  * @param   files
  1034.  *          The files to enumerate
  1035.  * @constructor
  1036.  */
  1037. function FileEnumerator(files) {
  1038.   if (files) {
  1039.     for (var i = 0; i < files.length; ++i) {
  1040.       if (!files[i])
  1041.         files.splice(i--, 1);
  1042.     }
  1043.     this._contents = files;
  1044.   } else {
  1045.     this._contents = [];
  1046.   }
  1047. }
  1048.  
  1049. FileEnumerator.prototype = {
  1050.   _index: 0,
  1051.  
  1052.   /**
  1053.    * Gets the next file in the sequence.
  1054.    */
  1055.   get nextFile() {
  1056.     if (this._index < this._contents.length)
  1057.       return this._contents[this._index++];
  1058.     return null;
  1059.   },
  1060.  
  1061.   /**
  1062.    * Stop enumerating. Nothing to do here.
  1063.    */
  1064.   close: function() {
  1065.   }
  1066. };
  1067.  
  1068. /**
  1069.  * An object which identifies an Install Location for items, where the location
  1070.  * relationship is each item living in a directory named with its GUID under
  1071.  * the directory used when constructing this object.
  1072.  *
  1073.  * e.g. <location>\{GUID1}
  1074.  *      <location>\{GUID2}
  1075.  *      <location>\{GUID3}
  1076.  *      ...
  1077.  *
  1078.  * @param   name
  1079.  *          The string identifier of this Install Location.
  1080.  * @param   location
  1081.  *          The directory that contains the items.
  1082.  * @constructor
  1083.  */
  1084. function DirectoryInstallLocation(name, location, restricted, priority, independent) {
  1085.   this._name = name;
  1086.   if (location.exists()) {
  1087.     if (!location.isDirectory())
  1088.       throw new Error("location must be a directoy!");
  1089.   }
  1090.   else {
  1091.     try {
  1092.       location.create(Ci.nsILocalFile.DIRECTORY_TYPE, 0775);
  1093.     }
  1094.     catch (e) {
  1095.       ERROR("DirectoryInstallLocation: failed to create location " +
  1096.             " directory = " + location.path + ", exception = " + e + "\n");
  1097.     }
  1098.   }
  1099.  
  1100.   this._location = location;
  1101.   this._locationToIDMap = {};
  1102.   this._restricted = restricted;
  1103.   this._priority = priority;
  1104.   this._independent = independent;
  1105. }
  1106. DirectoryInstallLocation.prototype = {
  1107.   _name           : "",
  1108.   _location       : null,
  1109.   _locationToIDMap: null,
  1110.   _restricted     : false,
  1111.   _priority       : 0,
  1112.   _independent    : false,
  1113.   _canAccess      : null,
  1114.  
  1115.   /**
  1116.    * See nsIExtensionManager.idl
  1117.    */
  1118.   get name() {
  1119.     return this._name;
  1120.   },
  1121.  
  1122.   /**
  1123.    * Reads a directory linked to in a file.
  1124.    * @param   file
  1125.    *          The file containing the directory path
  1126.    * @returns A nsILocalFile object representing the linked directory.
  1127.    */
  1128.   _readDirectoryFromFile: function(file) {
  1129.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  1130.               createInstance(Ci.nsIFileInputStream);
  1131.     fis.init(file, -1, -1, false);
  1132.     var line = { value: "" };
  1133.     if (fis instanceof Ci.nsILineInputStream)
  1134.       fis.readLine(line);
  1135.     fis.close();
  1136.     if (line.value) {
  1137.       var linkedDirectory = Cc["@mozilla.org/file/local;1"].
  1138.                             createInstance(Ci.nsILocalFile);
  1139.       try {
  1140.         linkedDirectory.initWithPath(line.value);
  1141.       }
  1142.       catch (e) {
  1143.         linkedDirectory.setRelativeDescriptor(file.parent, line.value);
  1144.       }
  1145.  
  1146.       return linkedDirectory;
  1147.     }
  1148.     return null;
  1149.   },
  1150.  
  1151.   /**
  1152.    * See nsIExtensionManager.idl
  1153.    */
  1154.   get itemLocations() {
  1155.     var locations = [];
  1156.     if (!this._location.exists())
  1157.       return new FileEnumerator(locations);
  1158.  
  1159.     try {
  1160.       var entries = this._location.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1161.       while (true) {
  1162.         var entry = entries.nextFile;
  1163.         if (!entry)
  1164.           break;
  1165.         entry instanceof Ci.nsILocalFile;
  1166.         if (!entry.isDirectory() && gIDTest.test(entry.leafName)) {
  1167.           var linkedDirectory = this._readDirectoryFromFile(entry);
  1168.           if (linkedDirectory && linkedDirectory.exists() &&
  1169.               linkedDirectory.isDirectory()) {
  1170.             locations.push(linkedDirectory);
  1171.             this._locationToIDMap[linkedDirectory.persistentDescriptor] = entry.leafName;
  1172.           }
  1173.         }
  1174.         else
  1175.           locations.push(entry);
  1176.       }
  1177.       entries.close();
  1178.     }
  1179.     catch (e) {
  1180.     }
  1181.     return new FileEnumerator(locations);
  1182.   },
  1183.  
  1184.   /**
  1185.    * Retrieves the GUID for an item at the specified location.
  1186.    * @param   file
  1187.    *          The location where an item might live.
  1188.    * @returns The ID for an item that might live at the location specified.
  1189.    *
  1190.    * N.B. This function makes no promises about whether or not this path is
  1191.    *      actually maintained by this Install Location.
  1192.    */
  1193.   getIDForLocation: function(file) {
  1194.     var section = file.leafName;
  1195.     var filePD = file.persistentDescriptor;
  1196.     if (filePD in this._locationToIDMap)
  1197.       section = this._locationToIDMap[filePD];
  1198.  
  1199.     if (gIDTest.test(section))
  1200.       return RegExp.$1;
  1201.     return undefined;
  1202.   },
  1203.  
  1204.   /**
  1205.    * See nsIExtensionManager.idl
  1206.    */
  1207.   get location() {
  1208.     return this._location.clone();
  1209.   },
  1210.  
  1211.   /**
  1212.    * See nsIExtensionManager.idl
  1213.    */
  1214.   get restricted() {
  1215.     return this._restricted;
  1216.   },
  1217.  
  1218.   /**
  1219.    * See nsIExtensionManager.idl
  1220.    */
  1221.   get canAccess() {
  1222.     if (this._canAccess != null)
  1223.       return this._canAccess;
  1224.  
  1225.     var testFile = this.location;
  1226.     testFile.append("Access Privileges Test");
  1227.     try {
  1228.       testFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1229.       testFile.remove(false);
  1230.       this._canAccess = true;
  1231.     }
  1232.     catch (e) {
  1233.       this._canAccess = false;
  1234.     }
  1235.     return this._canAccess;
  1236.   },
  1237.  
  1238.   /**
  1239.    * See nsIExtensionManager.idl
  1240.    */
  1241.   get priority() {
  1242.     return this._priority;
  1243.   },
  1244.  
  1245.   /**
  1246.    * See nsIExtensionManager.idl
  1247.    */
  1248.   getItemLocation: function(id) {
  1249.     var itemLocation = this.location;
  1250.     itemLocation.append(id);
  1251.     if (itemLocation.exists() && !itemLocation.isDirectory())
  1252.       return this._readDirectoryFromFile(itemLocation);
  1253.     if (!itemLocation.exists() && this.canAccess)
  1254.       itemLocation.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1255.     return itemLocation;
  1256.   },
  1257.  
  1258.   /**
  1259.    * See nsIExtensionManager.idl
  1260.    */
  1261.   itemIsManagedIndependently: function(id) {
  1262.     if (this._independent)
  1263.       return true;
  1264.     var itemLocation = this.location;
  1265.     itemLocation.append(id);
  1266.     return itemLocation.exists() && !itemLocation.isDirectory();
  1267.   },
  1268.  
  1269.   /**
  1270.    * See nsIExtensionManager.idl
  1271.    */
  1272.   getItemFile: function(id, filePath) {
  1273.     var itemLocation = this.getItemLocation(id).clone();
  1274.     var parts = filePath.split("/");
  1275.     for (var i = 0; i < parts.length; ++i)
  1276.       itemLocation.append(parts[i]);
  1277.     return itemLocation;
  1278.   },
  1279.  
  1280.   /**
  1281.    * Stages the specified file for later.
  1282.    * @param   file
  1283.    *          The file to stage
  1284.    * @param   id
  1285.    *          The GUID of the item the file represents
  1286.    */
  1287.   stageFile: function(file, id) {
  1288.     var stagedFile = this.location;
  1289.     stagedFile.append(DIR_STAGE);
  1290.     stagedFile.append(id);
  1291.     stagedFile.append(file.leafName);
  1292.  
  1293.     // When an incompatible update is successful the file is already staged
  1294.     if (stagedFile.equals(file))
  1295.       return stagedFile;
  1296.  
  1297.     if (stagedFile.exists())
  1298.       stagedFile.remove(false);
  1299.  
  1300.     file.copyTo(stagedFile.parent, stagedFile.leafName);
  1301.  
  1302.     // If the file has incorrect permissions set, correct them now.
  1303.     if (!stagedFile.isWritable())
  1304.       stagedFile.permissions = PERMS_FILE;
  1305.  
  1306.     return stagedFile;
  1307.   },
  1308.  
  1309.   /**
  1310.    * Returns the most recently staged package (e.g. the last XPI or JAR in a
  1311.    * directory) for an item and removes items that do not qualify.
  1312.    * @param   id
  1313.    *          The ID of the staged package
  1314.    * @returns an nsIFile if the package exists otherwise null.
  1315.    */
  1316.   getStageFile: function(id) {
  1317.     var stageFile = null;
  1318.     var stageDir = this.location;
  1319.     stageDir.append(DIR_STAGE);
  1320.     stageDir.append(id);
  1321.     if (!stageDir.exists() || !stageDir.isDirectory())
  1322.       return null;
  1323.     try {
  1324.       var entries = stageDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1325.       while (entries.hasMoreElements()) {
  1326.         var file = entries.nextFile;
  1327.         if (!(file instanceof Ci.nsILocalFile))
  1328.           continue;
  1329.         if (file.isDirectory())
  1330.           removeDirRecursive(file);
  1331.         else if (fileIsItemPackage(file)) {
  1332.           if (stageFile)
  1333.             stageFile.remove(false);
  1334.           stageFile = file;
  1335.         }
  1336.         else
  1337.           file.remove(false);
  1338.       }
  1339.     }
  1340.     catch (e) {
  1341.     }
  1342.     if (entries instanceof Ci.nsIDirectoryEnumerator)
  1343.       entries.close();
  1344.     return stageFile;
  1345.   },
  1346.  
  1347.   /**
  1348.    * Removes a file from the stage. This cleans up the stage if there is nothing
  1349.    * else left after the remove operation.
  1350.    * @param   file
  1351.    *          The file to remove.
  1352.    */
  1353.   removeFile: function(file) {
  1354.     if (file.exists())
  1355.       file.remove(false);
  1356.     var parent = file.parent;
  1357.     var entries = parent.directoryEntries;
  1358.     try {
  1359.       // XXXrstrong calling hasMoreElements on a nsIDirectoryEnumerator after
  1360.       // it has been removed will cause a crash on Mac OS X - bug 292823
  1361.       while (parent && !parent.equals(this.location) &&
  1362.             !entries.hasMoreElements()) {
  1363.         parent.remove(false);
  1364.         parent = parent.parent;
  1365.         entries = parent.directoryEntries;
  1366.       }
  1367.       if (entries instanceof Ci.nsIDirectoryEnumerator)
  1368.         entries.close();
  1369.     }
  1370.     catch (e) {
  1371.       ERROR("DirectoryInstallLocation::removeFile: failed to remove staged " +
  1372.             " directory = " + parent.path + ", exception = " + e + "\n");
  1373.     }
  1374.   },
  1375.  
  1376.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInstallLocation])
  1377. };
  1378.  
  1379. //@line 1499 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  1380.  
  1381. /**
  1382.  * An object which handles the installation of an Extension.
  1383.  * @constructor
  1384.  */
  1385. function Installer(ds, id, installLocation, type) {
  1386.   this._ds = ds;
  1387.   this._id = id;
  1388.   this._type = type;
  1389.   this._installLocation = installLocation;
  1390. }
  1391. Installer.prototype = {
  1392.   // Item metadata
  1393.   _id: null,
  1394.   _ds: null,
  1395.   _installLocation: null,
  1396.   _metadataDS: null,
  1397.  
  1398.   /**
  1399.    * Gets the Install Manifest datasource we are installing from.
  1400.    */
  1401.   get metadataDS() {
  1402.     if (!this._metadataDS) {
  1403.       var metadataFile = this._installLocation
  1404.                              .getItemFile(this._id, FILE_INSTALL_MANIFEST);
  1405.       if (!metadataFile.exists())
  1406.         return null;
  1407.       this._metadataDS = getInstallManifest(metadataFile);
  1408.       if (!this._metadataDS) {
  1409.         LOG("Installer::install: metadata datasource for extension " +
  1410.             this._id + " at " + metadataFile.path + " could not be loaded. " +
  1411.             " Installation will not proceed.");
  1412.       }
  1413.     }
  1414.     return this._metadataDS;
  1415.   },
  1416.  
  1417.   /**
  1418.    * Installs the Extension
  1419.    * @param   file
  1420.    *          A XPI/JAR file to install from. If this is null or does not exist,
  1421.    *          the item is assumed to be an expanded directory, located at the GUID
  1422.    *          key in the supplied Install Location.
  1423.    */
  1424.   installFromFile: function(file) {
  1425.     // Move files from the staging dir into the extension's final home.
  1426.     if (file && file.exists()) {
  1427.       this._installExtensionFiles(file);
  1428.     }
  1429.  
  1430.     if (!this.metadataDS)
  1431.       return;
  1432.  
  1433.     // Upgrade old-style contents.rdf Chrome Manifests if necessary.
  1434.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1435.       this.upgradeThemeChrome();
  1436.     else
  1437.       this.upgradeExtensionChrome();
  1438.  
  1439.     // Add metadata for the extension to the global extension metadata set
  1440.     this._ds.addItemMetadata(this._id, this.metadataDS, this._installLocation);
  1441.   },
  1442.  
  1443.   /**
  1444.    * Safely extract the Extension's files into the target folder.
  1445.    * @param   file
  1446.    *          The XPI/JAR file to install from.
  1447.    */
  1448.   _installExtensionFiles: function(file) {
  1449.     /**
  1450.       * Callback for |safeInstallOperation| that performs file level installation
  1451.       * steps for an Extension.
  1452.       * @param   extensionID
  1453.       *          The GUID of the Extension being installed.
  1454.       * @param   installLocation
  1455.       *          The Install Location where the Extension is being installed.
  1456.       * @param   xpiFile
  1457.       *          The source XPI file that contains the Extension.
  1458.       */
  1459.     function extractExtensionFiles(extensionID, installLocation, xpiFile) {
  1460.       // Create a logger to log install operations for uninstall. This must be
  1461.       // created in the |safeInstallOperation| callback, since it creates a file
  1462.       // in the target directory. If we do this outside of the callback, we may
  1463.       // be clobbering a file we should not be.
  1464.       var zipReader = getZipReaderForFile(xpiFile);
  1465.  
  1466.       // create directories first
  1467.       var entries = zipReader.findEntries("*/");
  1468.       while (entries.hasMore()) {
  1469.         var entryName = entries.getNext();
  1470.         var target = installLocation.getItemFile(extensionID, entryName);
  1471.         if (!target.exists()) {
  1472.           try {
  1473.             target.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1474.           }
  1475.           catch (e) {
  1476.             ERROR("extractExtensionsFiles: failed to create target directory for extraction " +
  1477.                   " file = " + target.path + ", exception = " + e + "\n");
  1478.           }
  1479.         }
  1480.       }
  1481.  
  1482.       entries = zipReader.findEntries(null);
  1483.       while (entries.hasMore()) {
  1484.         var entryName = entries.getNext();
  1485.         target = installLocation.getItemFile(extensionID, entryName);
  1486.         if (target.exists())
  1487.           continue;
  1488.  
  1489.         try {
  1490.           target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1491.         }
  1492.         catch (e) {
  1493.           ERROR("extractExtensionsFiles: failed to create target file for extraction " +
  1494.                 " file = " + target.path + ", exception = " + e + "\n");
  1495.         }
  1496.         zipReader.extract(entryName, target);
  1497.       }
  1498.       zipReader.close();
  1499.     }
  1500.  
  1501.     /**
  1502.       * Callback for |safeInstallOperation| that performs file level installation
  1503.       * steps for a Theme.
  1504.       * @param   id
  1505.       *          The GUID of the Theme being installed.
  1506.       * @param   installLocation
  1507.       *          The Install Location where the Theme is being installed.
  1508.       * @param   jarFile
  1509.       *          The source JAR file that contains the Theme.
  1510.       */
  1511.     function extractThemeFiles(id, installLocation, jarFile) {
  1512.       var themeDirectory = installLocation.getItemLocation(id);
  1513.       var zipReader = getZipReaderForFile(jarFile);
  1514.  
  1515.       // The only critical file is the install.rdf and we would not have
  1516.       // gotten this far without one.
  1517.       var rootFiles = [FILE_INSTALL_MANIFEST, FILE_CHROME_MANIFEST,
  1518.                        "preview.png", "icon.png"];
  1519.       for (var i = 0; i < rootFiles.length; ++i) {
  1520.         try {
  1521.           var target = installLocation.getItemFile(id, rootFiles[i]);
  1522.           zipReader.extract(rootFiles[i], target);
  1523.         }
  1524.         catch (e) {
  1525.         }
  1526.       }
  1527.  
  1528.       var manifestFile = installLocation.getItemFile(id, FILE_CHROME_MANIFEST);
  1529.       // new theme structure requires a chrome.manifest file
  1530.       if (manifestFile.exists()) {
  1531.         var entries = zipReader.findEntries(DIR_CHROME + "/*");
  1532.         while (entries.hasMore()) {
  1533.           var entryName = entries.getNext();
  1534.           if (entryName.charAt(entryName.length - 1) == "/")
  1535.             continue;
  1536.           target = installLocation.getItemFile(id, entryName);
  1537.           try {
  1538.             target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1539.           }
  1540.           catch (e) {
  1541.             ERROR("extractThemeFiles: failed to create target file for extraction " +
  1542.                   " file = " + target.path + ", exception = " + e + "\n");
  1543.           }
  1544.           zipReader.extract(entryName, target);
  1545.         }
  1546.         zipReader.close();
  1547.       }
  1548.       else { // old theme structure requires only an install.rdf
  1549.         try {
  1550.           var contentsManifestFile = installLocation.getItemFile(id, FILE_CONTENTS_MANIFEST);
  1551.           contentsManifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1552.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  1553.         }
  1554.         catch (e) {
  1555.           zipReader.close();
  1556.           ERROR("extractThemeFiles: failed to extract contents.rdf: " + target.path);
  1557.           throw e; // let the safe-op clean up
  1558.         }
  1559.         zipReader.close();
  1560.         var chromeDir = installLocation.getItemFile(id, DIR_CHROME);
  1561.         try {
  1562.           jarFile.copyTo(chromeDir, jarFile.leafName);
  1563.         }
  1564.         catch (e) {
  1565.           ERROR("extractThemeFiles: failed to copy theme JAR file to: " + chromeDir.path);
  1566.           throw e; // let the safe-op clean up
  1567.         }
  1568.  
  1569.         if (!installer.metadataDS && installer._type == Ci.nsIUpdateItem.TYPE_THEME) {
  1570.           var themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1571.           if (contentsManifestFile && contentsManifestFile.exists()) {
  1572.             var contentsManifest = gRDF.GetDataSourceBlocking(getURLSpecFromFile(contentsManifestFile));
  1573.             try {
  1574.               var ctr = getContainer(contentsManifest,
  1575.                                      gRDF.GetResource("urn:mozilla:skin:root"));
  1576.               var elts = ctr.GetElements();
  1577.               var nameArc = gRDF.GetResource(CHROME_NS("displayName"));
  1578.               while (elts.hasMoreElements()) {
  1579.                 var elt = elts.getNext().QueryInterface(Ci.nsIRDFResource);
  1580.                 themeName = stringData(contentsManifest.GetTarget(elt, nameArc, true));
  1581.                 if (themeName)
  1582.                   break;
  1583.               }
  1584.             }
  1585.             catch (e) {
  1586.               themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1587.             }
  1588.           }
  1589.           showIncompatibleError({ name: themeName, version: "",
  1590.                                   type: Ci.nsIUpdateItem.TYPE_THEME });
  1591.           LOG("Theme JAR file: " + jarFile.leafName + " contains an Old-Style " +
  1592.               "Theme that is not compatible with this version of the software.");
  1593.           throw new Error("Old Theme"); // let the safe-op clean up
  1594.         }
  1595.       }
  1596.     }
  1597.  
  1598.     var installer = this;
  1599.     var callback = extractExtensionFiles;
  1600.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1601.       callback = extractThemeFiles;
  1602.     safeInstallOperation(this._id, this._installLocation,
  1603.                           { callback: callback, data: file });
  1604.   },
  1605.  
  1606.   /**
  1607.    * Upgrade contents.rdf Chrome Manifests used by this Theme to the new
  1608.    * chrome.manifest format if necessary.
  1609.    */
  1610.   upgradeThemeChrome: function() {
  1611.     // Use the Chrome Registry API to install the theme there
  1612.     var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1613.              getService(Ci.nsIToolkitChromeRegistry);
  1614.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1615.     if (manifestFile.exists() ||
  1616.         this._id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  1617.       return;
  1618.  
  1619.     try {
  1620.       // creates a chrome manifest for themes
  1621.       var manifestURI = getURIFromFile(manifestFile);
  1622.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1623.       // We're relying on the fact that there is only one JAR file
  1624.       // in the "chrome" directory. This is a hack, but it works.
  1625.       var entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1626.       var jarFile = entries.nextFile;
  1627.       if (jarFile) {
  1628.         var jarFileURI = getURIFromFile(jarFile);
  1629.         var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  1630.         var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1631.         var contentsFileURI = getURIFromFile(contentsFile.parent);
  1632.  
  1633.         cr.processContentsManifest(contentsFileURI, manifestURI, contentsURI, false, true);
  1634.       }
  1635.       entries.close();
  1636.       contentsFile.remove(false);
  1637.     }
  1638.     catch (e) {
  1639.       // Failed to register chrome, for any number of reasons - non-existent
  1640.       // contents.rdf file at the location specified, malformed contents.rdf,
  1641.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1642.       // extension is uninstalled properly during the subsequent uninstall
  1643.       // pass in |ExtensionManager::_finishOperations|
  1644.       ERROR("upgradeThemeChrome: failed for theme " + this._id + " - why " +
  1645.             "not convert to the new chrome.manifest format while you're at it? " +
  1646.             "Failure exception: " + e);
  1647.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1648.                   [BundleManager.appName]);
  1649.  
  1650.       var stageFile = this._installLocation.getStageFile(this._id);
  1651.       if (stageFile)
  1652.         this._installLocation.removeFile(stageFile);
  1653.  
  1654.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1655.       StartupCache.write();
  1656.     }
  1657.   },
  1658.  
  1659.   /**
  1660.    * Upgrade contents.rdf Chrome Manifests used by this Extension to the new
  1661.    * chrome.manifest format if necessary.
  1662.    */
  1663.   upgradeExtensionChrome: function() {
  1664.     // If the extension is aware of the new flat chrome manifests and has
  1665.     // included one, just use it instead of generating one from the
  1666.     // install.rdf/contents.rdf data.
  1667.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1668.     if (manifestFile.exists())
  1669.       return;
  1670.  
  1671.     try {
  1672.       // Enumerate the metadata datasource files collection and register chrome
  1673.       // for each file, calling _registerChrome for each.
  1674.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1675.  
  1676.       if (!manifestFile.parent.exists())
  1677.         return;
  1678.  
  1679.       // Even if an extension doesn't have any chrome, we generate an empty
  1680.       // manifest file so that we don't try to upgrade from the "old-style"
  1681.       // chrome manifests at every startup.
  1682.       manifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1683.  
  1684.       var manifestURI = getURIFromFile(manifestFile);
  1685.       var files = this.metadataDS.GetTargets(gInstallManifestRoot, EM_R("file"), true);
  1686.       while (files.hasMoreElements()) {
  1687.         var file = files.getNext().QueryInterface(Ci.nsIRDFResource);
  1688.         var chromeFile = chromeDir.clone();
  1689.         var fileName = file.Value.substr("urn:mozilla:extension:file:".length, file.Value.length);
  1690.         chromeFile.append(fileName);
  1691.  
  1692.         var fileURLSpec = getURLSpecFromFile(chromeFile);
  1693.         if (!chromeFile.isDirectory()) {
  1694.           var zipReader = getZipReaderForFile(chromeFile);
  1695.           fileURLSpec = "jar:" + fileURLSpec + "!/";
  1696.           var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1697.           contentsFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1698.         }
  1699.  
  1700.         var providers = [EM_R("package"), EM_R("skin"), EM_R("locale")];
  1701.         for (var i = 0; i < providers.length; ++i) {
  1702.           var items = this.metadataDS.GetTargets(file, providers[i], true);
  1703.           while (items.hasMoreElements()) {
  1704.             var item = items.getNext().QueryInterface(Ci.nsIRDFLiteral);
  1705.             var fileURI = newURI(fileURLSpec + item.Value);
  1706.             // Extract the contents.rdf files instead of opening them inside of
  1707.             // the jar. This prevents the jar from being cached by the zip
  1708.             // reader which will keep the jar in use and prevent deletion.
  1709.             if (zipReader) {
  1710.               zipReader.extract(item.Value + FILE_CONTENTS_MANIFEST, contentsFile);
  1711.               var contentsFileURI = getURIFromFile(contentsFile.parent);
  1712.             }
  1713.             else
  1714.               contentsFileURI = fileURI;
  1715.  
  1716.             var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1717.                      getService(Ci.nsIToolkitChromeRegistry);
  1718.             cr.processContentsManifest(contentsFileURI, manifestURI, fileURI, true, false);
  1719.           }
  1720.         }
  1721.         if (zipReader) {
  1722.           zipReader.close();
  1723.           zipReader = null;
  1724.           contentsFile.remove(false);
  1725.         }
  1726.       }
  1727.     }
  1728.     catch (e) {
  1729.       // Failed to register chrome, for any number of reasons - non-existent
  1730.       // contents.rdf file at the location specified, malformed contents.rdf,
  1731.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1732.       // extension is uninstalled properly during the subsequent uninstall
  1733.       // pass in |ExtensionManager::_finishOperations|
  1734.       ERROR("upgradeExtensionChrome: failed for extension " + this._id + " - why " +
  1735.             "not convert to the new chrome.manifest format while you're at it? " +
  1736.             "Failure exception: " + e);
  1737.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1738.                   [BundleManager.appName]);
  1739.  
  1740.       var stageFile = this._installLocation.getStageFile(this._id);
  1741.       if (stageFile)
  1742.         this._installLocation.removeFile(stageFile);
  1743.  
  1744.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1745.       StartupCache.write();
  1746.     }
  1747.   }
  1748. };
  1749.  
  1750. /**
  1751.  * Safely attempt to perform a caller-defined install operation for a given
  1752.  * item ID. Using aggressive success-safety checks, this function will attempt
  1753.  * to move an existing location for an item aside and then allow installation
  1754.  * into the appropriate folder. If any operation fails the installation will
  1755.  * abort and roll back from the moved-aside old version.
  1756.  * @param   itemID
  1757.  *          The GUID of the item to perform the operation on.
  1758.  * @param   installLocation
  1759.  *          The Install Location where the item is installed.
  1760.  * @param   installCallback
  1761.  *          A caller supplied JS object with the following properties:
  1762.  *          "data"      A data parameter to be passed to the callback.
  1763.  *          "callback"  A function to perform the install operation. This
  1764.  *                      function is passed three parameters:
  1765.  *                      1. The GUID of the item being operated on.
  1766.  *                      2. The Install Location where the item is installed.
  1767.  *                      3. The "data" parameter on the installCallback object.
  1768.  */
  1769. function safeInstallOperation(itemID, installLocation, installCallback) {
  1770.   var movedFiles = [];
  1771.  
  1772.   /**
  1773.    * Reverts a deep move by moving backed up files back to their original
  1774.    * location.
  1775.    */
  1776.   function rollbackMove()
  1777.   {
  1778.     for (var i = 0; i < movedFiles.length; ++i) {
  1779.       var oldFile = movedFiles[i].oldFile;
  1780.       var newFile = movedFiles[i].newFile;
  1781.       try {
  1782.         newFile.moveTo(oldFile.parent, newFile.leafName);
  1783.       }
  1784.       catch (e) {
  1785.         ERROR("safeInstallOperation: failed to roll back files after an install " +
  1786.               "operation failed. Failed to roll back: " + newFile.path + " to: " +
  1787.               oldFile.path + " ... aborting installation.");
  1788.         throw e;
  1789.       }
  1790.     }
  1791.   }
  1792.  
  1793.   /**
  1794.    * Moves a file to a new folder.
  1795.    * @param   file
  1796.    *          The file to move
  1797.    * @param   destination
  1798.    *          The target folder
  1799.    */
  1800.   function moveFile(file, destination) {
  1801.     try {
  1802.       var oldFile = file.clone();
  1803.       file.moveTo(destination, file.leafName);
  1804.       movedFiles.push({ oldFile: oldFile, newFile: file });
  1805.     }
  1806.     catch (e) {
  1807.       ERROR("safeInstallOperation: failed to back up file: " + file.path + " to: " +
  1808.             destination.path + " ... rolling back file moves and aborting " +
  1809.             "installation.");
  1810.       rollbackMove();
  1811.       throw e;
  1812.     }
  1813.   }
  1814.  
  1815.   /**
  1816.    * Moves a directory to a new location. If any part of the move fails,
  1817.    * files already moved will be rolled back.
  1818.    * @param   sourceDir
  1819.    *          The directory to move
  1820.    * @param   targetDir
  1821.    *          The destination directory
  1822.    * @param   currentDir
  1823.    *          The current directory (a subdirectory of |sourceDir| or
  1824.    *          |sourceDir| itself) we are moving files from.
  1825.    */
  1826.   function moveDirectory(sourceDir, targetDir, currentDir) {
  1827.     var entries = currentDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1828.     while (true) {
  1829.       var entry = entries.nextFile;
  1830.       if (!entry)
  1831.         break;
  1832.       if (entry.isDirectory())
  1833.         moveDirectory(sourceDir, targetDir, entry);
  1834.       else if (entry instanceof Ci.nsILocalFile) {
  1835.         var rd = entry.getRelativeDescriptor(sourceDir);
  1836.         var destination = targetDir.clone().QueryInterface(Ci.nsILocalFile);
  1837.         destination.setRelativeDescriptor(targetDir, rd);
  1838.         moveFile(entry, destination.parent);
  1839.       }
  1840.     }
  1841.     entries.close();
  1842.   }
  1843.  
  1844.   /**
  1845.    * Removes the temporary backup directory where we stored files.
  1846.    * @param   directory
  1847.    *          The backup directory to remove
  1848.    */
  1849.   function cleanUpTrash(directory) {
  1850.     try {
  1851.       // Us-generated. Safe.
  1852.       if (directory && directory.exists())
  1853.         removeDirRecursive(directory);
  1854.     }
  1855.     catch (e) {
  1856.       ERROR("safeInstallOperation: failed to clean up the temporary backup of the " +
  1857.             "older version: " + itemLocationTrash.path);
  1858.       // This is a non-fatal error. Annoying, but non-fatal.
  1859.     }
  1860.   }
  1861.  
  1862.   if (!installLocation.itemIsManagedIndependently(itemID)) {
  1863.     var itemLocation = installLocation.getItemLocation(itemID);
  1864.     if (itemLocation.exists()) {
  1865.       var trashDirName = itemID + "-trash";
  1866.       var itemLocationTrash = itemLocation.parent.clone();
  1867.       itemLocationTrash.append(trashDirName);
  1868.       if (itemLocationTrash.exists()) {
  1869.         // We can remove recursively here since this is a folder we created, not
  1870.         // one the user specified. If this fails, it'll throw, and the caller
  1871.         // should stop installation.
  1872.         try {
  1873.           removeDirRecursive(itemLocationTrash);
  1874.         }
  1875.         catch (e) {
  1876.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  1877.                 itemLocationTrash.path + " ... aborting installation.");
  1878.           throw e;
  1879.         }
  1880.       }
  1881.  
  1882.       // Move the directory that contains the existing version of the item aside,
  1883.       // into {GUID}-trash. This will throw if there's a failure and the install
  1884.       // will abort.
  1885.       moveDirectory(itemLocation, itemLocationTrash, itemLocation);
  1886.  
  1887.       // Clean up the original location, if necessary. Again, this is a path we
  1888.       // generated, so it is safe to recursively delete.
  1889.       try {
  1890.         removeDirRecursive(itemLocation);
  1891.       }
  1892.       catch (e) {
  1893.         ERROR("safeInstallOperation: failed to clean up item location after its contents " +
  1894.               "were properly backed up. Failed to clean up: " + itemLocation.path +
  1895.               " ... rolling back file moves and aborting installation.");
  1896.         rollbackMove();
  1897.         cleanUpTrash(itemLocationTrash);
  1898.         throw e;
  1899.       }
  1900.     }
  1901.   }
  1902.   else if (installLocation.name == KEY_APP_PROFILE ||
  1903.            installLocation.name == KEY_APP_GLOBAL ||
  1904.            installLocation.name == KEY_APP_SYSTEM_USER) {
  1905.     // Check for a pointer file and move it aside if it exists
  1906.     var pointerFile = installLocation.location.clone();
  1907.     pointerFile.append(itemID);
  1908.     if (pointerFile.exists() && !pointerFile.isDirectory()) {
  1909.       var trashFileName = itemID + "-trash";
  1910.       var itemLocationTrash = installLocation.location.clone();
  1911.       itemLocationTrash.append(trashFileName);
  1912.       if (itemLocationTrash.exists()) {
  1913.         // We can remove recursively here since this is a folder we created, not
  1914.         // one the user specified. If this fails, it'll throw, and the caller
  1915.         // should stop installation.
  1916.         try {
  1917.           removeDirRecursive(itemLocationTrash);
  1918.         }
  1919.         catch (e) {
  1920.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  1921.                 itemLocationTrash.path + " ... aborting installation.");
  1922.           throw e;
  1923.         }
  1924.       }
  1925.       itemLocationTrash.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1926.       // Move the pointer file to the trash.
  1927.       moveFile(pointerFile, itemLocationTrash);
  1928.     }
  1929.   }
  1930.  
  1931.   // Now tell the client to do their stuff.
  1932.   try {
  1933.     installCallback.callback(itemID, installLocation, installCallback.data);
  1934.   }
  1935.   catch (e) {
  1936.     // This means the install operation failed. Remove everything and roll back.
  1937.     ERROR("safeInstallOperation: install operation (caller-supplied callback) failed, " +
  1938.           "rolling back file moves and aborting installation.");
  1939.     try {
  1940.       // Us-generated. Safe.
  1941.       removeDirRecursive(itemLocation);
  1942.     }
  1943.     catch (e) {
  1944.       ERROR("safeInstallOperation: failed to remove the folder we failed to install " +
  1945.             "an item into: " + itemLocation.path + " -- There is not much to suggest " +
  1946.             "here... maybe restart and try again?");
  1947.       cleanUpTrash(itemLocationTrash);
  1948.       throw e;
  1949.     }
  1950.     rollbackMove();
  1951.     cleanUpTrash(itemLocationTrash);
  1952.     throw e;
  1953.   }
  1954.  
  1955.   // Now, and only now - after everything else has succeeded (against all odds!)
  1956.   // remove the {GUID}-trash directory where we stashed the old version of the
  1957.   // item.
  1958.   cleanUpTrash(itemLocationTrash);
  1959. }
  1960.  
  1961. /**
  1962.  * Manages the list of pending operations.
  1963.  */
  1964. var PendingOperations = {
  1965.   _ops: { },
  1966.  
  1967.   /**
  1968.    * Adds an entry to the Pending Operations List
  1969.    * @param   opType
  1970.    *          The type of Operation to be performed
  1971.    * @param   entry
  1972.    *          A JS Object representing the item to be operated on:
  1973.    *          "locationKey"   The name of the Install Location where the item
  1974.    *                          is installed.
  1975.    *          "id"            The GUID of the item.
  1976.    */
  1977.   addItem: function(opType, entry) {
  1978.     if (opType == OP_NONE)
  1979.       this.clearOpsForItem(entry.id);
  1980.     else {
  1981.       if (!(opType in this._ops))
  1982.         this._ops[opType] = { };
  1983.       this._ops[opType][entry.id] = entry.locationKey;
  1984.     }
  1985.   },
  1986.  
  1987.   /**
  1988.    * Removes a Pending Operation from the list
  1989.    * @param   opType
  1990.    *          The type of Operation being removed
  1991.    * @param   id
  1992.    *          The GUID of the item to remove the entry for
  1993.    */
  1994.   clearItem: function(opType, id) {
  1995.     if (opType in this._ops && id in this._ops[opType])
  1996.       delete this._ops[opType][id];
  1997.   },
  1998.  
  1999.   /**
  2000.    * Removes all Pending Operation for an item
  2001.    * @param   id
  2002.    *          The ID of the item to remove the entries for
  2003.    */
  2004.   clearOpsForItem: function(id) {
  2005.     for (var opType in this._ops) {
  2006.       if (id in this._ops[opType])
  2007.         delete this._ops[opType][id];
  2008.     }
  2009.   },
  2010.  
  2011.   /**
  2012.    * Remove all Pending Operations of a certain type
  2013.    * @param   opType
  2014.    *          The type of Operation to remove all entries for
  2015.    */
  2016.   clearItems: function(opType) {
  2017.     if (opType in this._ops)
  2018.       delete this._ops[opType];
  2019.   },
  2020.  
  2021.   /**
  2022.    * Get an array of operations of a certain type
  2023.    * @param   opType
  2024.    *          The type of Operation to return a list of
  2025.    */
  2026.   getOperations: function(opType) {
  2027.     if (!(opType in this._ops))
  2028.       return [];
  2029.     var ops = [];
  2030.     for (var id in this._ops[opType])
  2031.       ops.push( {id: id, locationKey: this._ops[opType][id] } );
  2032.     return ops;
  2033.   },
  2034.  
  2035.   /**
  2036.    * The total number of Pending Operations, for all types.
  2037.    */
  2038.   get size() {
  2039.     var size = 0;
  2040.     for (var opType in this._ops) {
  2041.       for (var id in this._ops[opType])
  2042.         ++size;
  2043.     }
  2044.     return size;
  2045.   }
  2046. };
  2047.  
  2048. /**
  2049.  * Manages registered Install Locations
  2050.  */
  2051. var InstallLocations = {
  2052.   _locations: { },
  2053.  
  2054.   /**
  2055.    * A nsISimpleEnumerator of all available Install Locations.
  2056.    */
  2057.   get enumeration() {
  2058.     var installLocations = [];
  2059.     for (var key in this._locations)
  2060.       installLocations.push(InstallLocations.get(key));
  2061.     return new ArrayEnumerator(installLocations);
  2062.   },
  2063.  
  2064.   /**
  2065.    * Gets a named Install Location
  2066.    * @param   name
  2067.    *          The name of the Install Location to get
  2068.    */
  2069.   get: function(name) {
  2070.     return name in this._locations ? this._locations[name] : null;
  2071.   },
  2072.  
  2073.   /**
  2074.    * Registers an Install Location
  2075.    * @param   installLocation
  2076.    *          The Install Location to register
  2077.    */
  2078.   put: function(installLocation) {
  2079.     this._locations[installLocation.name] = installLocation;
  2080.   }
  2081. };
  2082.  
  2083. /**
  2084.  * Manages the Startup Cache. The Startup Cache is a representation
  2085.  * of the contents of extensions.cache, a list of all
  2086.  * items the Extension System knows about, whether or not they
  2087.  * are active or visible.
  2088.  */
  2089. var StartupCache = {
  2090.   /**
  2091.    * Location Name -> GUID hash of entries from the Startup Cache file
  2092.    * Each entry has the following properties:
  2093.    *  "descriptor"    The location on disk of the item
  2094.    *  "mtime"         The time the location was last modified
  2095.    *  "op"            Any pending operations on this item.
  2096.    *  "location"      The Install Location name where the item is installed.
  2097.    */
  2098.   entries: { },
  2099.  
  2100.   /**
  2101.    * Puts an entry into the Startup Cache
  2102.    * @param   installLocation
  2103.    *          The Install Location where the item is installed
  2104.    * @param   id
  2105.    *          The GUID of the item
  2106.    * @param   op
  2107.    *          The name of the operation to be performed
  2108.    * @param   shouldCreate
  2109.    *          Whether or not we should create a new entry for this item
  2110.    *          in the cache if one does not already exist.
  2111.    */
  2112.   put: function(installLocation, id, op, shouldCreate) {
  2113.     var itemLocation = installLocation.getItemLocation(id);
  2114.  
  2115.     var descriptor = null;
  2116.     var mtime = null;
  2117.     if (itemLocation) {
  2118.       itemLocation.QueryInterface(Ci.nsILocalFile);
  2119.       descriptor = getDescriptorFromFile(itemLocation, installLocation);
  2120.       if (itemLocation.exists() && itemLocation.isDirectory())
  2121.         mtime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2122.     }
  2123.  
  2124.     this._putRaw(installLocation.name, id, descriptor, mtime, op, shouldCreate);
  2125.   },
  2126.  
  2127.   /**
  2128.    * Private helper function for putting an entry into the Startup Cache
  2129.    * without relying on the presence of its associated nsIInstallLocation
  2130.    * instance.
  2131.    *
  2132.    * @param key
  2133.    *        The install location name.
  2134.    * @param id
  2135.    *        The ID of the item.
  2136.    * @param descriptor
  2137.    *        Value returned from absoluteDescriptor.  May be null, in which
  2138.    *        case the descriptor field is not updated.
  2139.    * @param mtime
  2140.    *        The last modified time of the item.  May be null, in which case the
  2141.    *        descriptor field is not updated.
  2142.    * @param op
  2143.    *        The OP code to store with the entry.
  2144.    * @param shouldCreate
  2145.    *        Boolean value indicating whether to create or delete the entry.
  2146.    */
  2147.   _putRaw: function(key, id, descriptor, mtime, op, shouldCreate) {
  2148.     if (!(key in this.entries))
  2149.       this.entries[key] = { };
  2150.     if (!(id in this.entries[key]))
  2151.       this.entries[key][id] = { };
  2152.     if (shouldCreate) {
  2153.       if (!this.entries[key][id])
  2154.         this.entries[key][id] = { };
  2155.  
  2156.       var entry = this.entries[key][id];
  2157.  
  2158.       if (descriptor)
  2159.         entry.descriptor = descriptor;
  2160.       if (mtime)
  2161.         entry.mtime = mtime;
  2162.       entry.op = op;
  2163.       entry.location = key;
  2164.     }
  2165.     else
  2166.       this.entries[key][id] = null;
  2167.   },
  2168.  
  2169.   /**
  2170.    * Clears an entry from the Startup Cache
  2171.    * @param   installLocation
  2172.    *          The Install Location where item is installed
  2173.    * @param   id
  2174.    *          The GUID of the item.
  2175.    */
  2176.   clearEntry: function(installLocation, id) {
  2177.     var key = installLocation.name;
  2178.     if (key in this.entries && id in this.entries[key])
  2179.       this.entries[key][id] = null;
  2180.   },
  2181.  
  2182.   /**
  2183.    * Get all the startup cache entries for a particular ID.
  2184.    * @param   id
  2185.    *          The GUID of the item to locate.
  2186.    * @returns An array of Startup Cache entries for the specified ID.
  2187.    */
  2188.   findEntries: function(id) {
  2189.     var entries = [];
  2190.     for (var key in this.entries) {
  2191.       if (id in this.entries[key])
  2192.         entries.push(this.entries[key][id]);
  2193.     }
  2194.     return entries;
  2195.   },
  2196.  
  2197.   /**
  2198.    * Read the Item-Change manifest file into a hash of properties.
  2199.    * The Item-Change manifest currently holds a list of paths, with the last
  2200.    * mtime for each path, and the GUID of the item at that path.
  2201.    */
  2202.   read: function() {
  2203.     var itemChangeManifest = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2204.     if (!itemChangeManifest.exists()) {
  2205.       // There is no change manifest for some reason, either we're in an initial
  2206.       // state or something went wrong with one of the other files and the
  2207.       // change manifest was removed. Return an empty dataset and rebuild.
  2208.       gFirstRun = true;
  2209.       return;
  2210.     }
  2211.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  2212.               createInstance(Ci.nsIFileInputStream);
  2213.     fis.init(itemChangeManifest, -1, -1, false);
  2214.     if (fis instanceof Ci.nsILineInputStream) {
  2215.       var line = { value: "" };
  2216.       var more = false;
  2217.       do {
  2218.         more = fis.readLine(line);
  2219.         if (line.value) {
  2220.           // The Item-Change manifest is formatted like so:
  2221.           //  (pd = descriptor)
  2222.           // location-key\tguid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2223.           // location-key\tguid-of-item\tpd-to-extension2\tmtime-of-pd\tpending-op
  2224.           // ...
  2225.           // We hash on location-key first, because we don't want to have to
  2226.           // spin up the main extensions datasource on every start to determine
  2227.           // the Install Location for an item.
  2228.           // We hash on guid second, because we want a way to quickly determine
  2229.           // item GUID during a check loop that runs on every startup.
  2230.           var parts = line.value.split("\t");
  2231.           // Silently drop any entries in unknown install locations
  2232.           if (!InstallLocations.get(parts[0]))
  2233.             continue;
  2234.           var op = parts[4];
  2235.           this._putRaw(parts[0], parts[1], parts[2], parts[3], op, true);
  2236.           if (op)
  2237.             PendingOperations.addItem(op, { locationKey: parts[0], id: parts[1] });
  2238.         }
  2239.       }
  2240.       while (more);
  2241.     }
  2242.     fis.close();
  2243.   },
  2244.  
  2245.   /**
  2246.    * Writes the Startup Cache to disk
  2247.    */
  2248.   write: function() {
  2249.     var extensionsCacheFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2250.     var fos = openSafeFileOutputStream(extensionsCacheFile);
  2251.     for (var locationKey in this.entries) {
  2252.       for (var id in this.entries[locationKey]) {
  2253.         var entry = this.entries[locationKey][id];
  2254.         if (entry) {
  2255.           try {
  2256.             var itemLocation = getFileFromDescriptor(entry.descriptor, InstallLocations.get(locationKey));
  2257.  
  2258.             // Update our knowledge of this item's last-modified-time.
  2259.             // XXXdarin: this may cause us to miss changes in some cases.
  2260.             var itemMTime = 0;
  2261.             if (itemLocation.exists() && itemLocation.isDirectory())
  2262.               itemMTime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2263.  
  2264.             // Each line in the startup cache manifest is in this form:
  2265.             // location-key\tid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2266.             var line = locationKey + "\t" + id + "\t" + entry.descriptor + "\t" +
  2267.                        itemMTime + "\t" + entry.op + "\r\n";
  2268.             fos.write(line, line.length);
  2269.           }
  2270.           catch (e) {}
  2271.         }
  2272.       }
  2273.     }
  2274.     closeSafeFileOutputStream(fos);
  2275.   }
  2276. };
  2277.  
  2278. /**
  2279.  * Installs, manages and tracks compatibility for Extensions and Themes
  2280.  * @constructor
  2281.  */
  2282. function ExtensionManager() {
  2283.   gApp = Cc["@mozilla.org/xre/app-info;1"].
  2284.          getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);
  2285.   gOSTarget = gApp.OS;
  2286.   try {
  2287.     gXPCOMABI = gApp.XPCOMABI;
  2288.   } catch (ex) {
  2289.     // Provide a default for gXPCOMABI. It won't be compared to an
  2290.     // item's metadata (i.e. install.rdf can't specify e.g. WINNT_unknownABI
  2291.     // as targetPlatform), but it will be displayed in error messages and
  2292.     // transmitted to update URLs.
  2293.     gXPCOMABI = UNKNOWN_XPCOM_ABI;
  2294.   }
  2295.   gPref = Cc["@mozilla.org/preferences-service;1"].
  2296.           getService(Ci.nsIPrefBranch2);
  2297.  
  2298.   gOS = Cc["@mozilla.org/observer-service;1"].
  2299.         getService(Ci.nsIObserverService);
  2300.   gOS.addObserver(this, "xpcom-shutdown", false);
  2301.  
  2302.   gConsole = Cc["@mozilla.org/consoleservice;1"].
  2303.              getService(Ci.nsIConsoleService);
  2304.  
  2305.   gRDF = Cc["@mozilla.org/rdf/rdf-service;1"].
  2306.          getService(Ci.nsIRDFService);
  2307.   gInstallManifestRoot = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
  2308.  
  2309.   // Register Global Install Location
  2310.   var appGlobalExtensions = getDirNoCreate(KEY_APPDIR, [DIR_EXTENSIONS]);
  2311.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL;
  2312.   var globalLocation = new DirectoryInstallLocation(KEY_APP_GLOBAL,
  2313.                                                     appGlobalExtensions, true,
  2314.                                                     priority, false);
  2315.   InstallLocations.put(globalLocation);
  2316.  
  2317.   // Register App-Profile Install Location
  2318.   var appProfileExtensions = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS]);
  2319.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_PROFILE;
  2320.   var profileLocation = new DirectoryInstallLocation(KEY_APP_PROFILE,
  2321.                                                      appProfileExtensions, false,
  2322.                                                      priority, false);
  2323.   InstallLocations.put(profileLocation);
  2324.  
  2325.   // Register per-user Install Location
  2326.   try {
  2327.     var appSystemUExtensions = getDirNoCreate("XREUSysExt", [gApp.ID]);
  2328.   }
  2329.   catch(e) { }
  2330.  
  2331.   if (appSystemUExtensions) {
  2332.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_USER;
  2333.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_USER,
  2334.                                                       appSystemUExtensions, false,
  2335.                                                       priority, true);
  2336.  
  2337.     InstallLocations.put(systemLocation);
  2338.   }
  2339.  
  2340.   // Register App-System-Shared Install Location
  2341.   try {
  2342.     var appSystemSExtensions = getDirNoCreate("XRESysSExtPD", [gApp.ID]);
  2343.   }
  2344.   catch (e) { }
  2345.  
  2346.   if (appSystemSExtensions) {
  2347.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 10;
  2348.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_SHARE,
  2349.                                                       appSystemSExtensions, true,
  2350.                                                       priority, true);
  2351.     InstallLocations.put(systemLocation);
  2352.   }
  2353.  
  2354.   // Register App-System-Local Install Location
  2355.   try {
  2356.     var appSystemLExtensions = getDirNoCreate("XRESysLExtPD", [gApp.ID]);
  2357.   }
  2358.   catch (e) { }
  2359.  
  2360.   if (appSystemLExtensions) {
  2361.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 20;
  2362.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_LOCAL,
  2363.                                                       appSystemLExtensions, true,
  2364.                                                       priority, true);
  2365.     InstallLocations.put(systemLocation);
  2366.   }
  2367.  
  2368. //@line 2502 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  2369.  
  2370.   // Register Additional Install Locations
  2371.   var categoryManager = Cc["@mozilla.org/categorymanager;1"].
  2372.                         getService(Ci.nsICategoryManager);
  2373.   var locations = categoryManager.enumerateCategory(CATEGORY_INSTALL_LOCATIONS);
  2374.   while (locations.hasMoreElements()) {
  2375.     var entry = locations.getNext().QueryInterface(Ci.nsISupportsCString).data;
  2376.     var contractID = categoryManager.getCategoryEntry(CATEGORY_INSTALL_LOCATIONS, entry);
  2377.     var location = Cc[contractID].getService(Ci.nsIInstallLocation);
  2378.     InstallLocations.put(location);
  2379.   }
  2380. }
  2381.  
  2382. ExtensionManager.prototype = {
  2383.   /**
  2384.    * See nsIObserver.idl
  2385.    */
  2386.   observe: function(subject, topic, data) {
  2387.     switch (topic) {
  2388.     case "app-startup":
  2389.       gOS.addObserver(this, "profile-after-change", false);
  2390.       gOS.addObserver(this, "quit-application", false);
  2391.       break;
  2392.     case "profile-after-change":
  2393.       this._profileSelected();
  2394.       break;
  2395.     case "quit-application-requested":
  2396.       this._confirmCancelDownloadsOnQuit(subject);
  2397.       break;
  2398.     case "offline-requested":
  2399.       this._confirmCancelDownloadsOnOffline(subject);
  2400.       break;
  2401.     case "quit-application":
  2402.       gOS.removeObserver(this, "profile-after-change");
  2403.       gOS.removeObserver(this, "quit-application");
  2404.       break;
  2405.     case "xpcom-shutdown":
  2406.       this._shutdown();
  2407.       break;
  2408.     case "nsPref:changed":
  2409.       if (data == PREF_EM_LOGGING_ENABLED)
  2410.         this._loggingToggled();
  2411.       else if (data == PREF_EM_CHECK_COMPATIBILITY ||
  2412.                data == PREF_EM_CHECK_UPDATE_SECURITY)
  2413.         this._updateAppDisabledState();
  2414.       else if ((data == PREF_MATCH_OS_LOCALE) || (data == PREF_SELECTED_LOCALE))
  2415.         this._updateLocale();
  2416.       break;
  2417.     }
  2418.   },
  2419.  
  2420.   /**
  2421.    * Refresh the logging enabled global from preferences when the user changes
  2422.    * the preference settting.
  2423.    */
  2424.   _loggingToggled: function() {
  2425.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2426.   },
  2427.  
  2428.   /**
  2429.    * Retrieves the current locale
  2430.    */
  2431.   _updateLocale: function() {
  2432.     try {
  2433.       if (gPref.getBoolPref(PREF_MATCH_OS_LOCALE)) {
  2434.         var localeSvc = Cc["@mozilla.org/intl/nslocaleservice;1"].
  2435.                         getService(Ci.nsILocaleService);
  2436.         gLocale = localeSvc.getLocaleComponentForUserAgent();
  2437.         return;
  2438.       }
  2439.     }
  2440.     catch (ex) {
  2441.     }
  2442.     gLocale = gPref.getCharPref(PREF_SELECTED_LOCALE);
  2443.   },
  2444.  
  2445.   /**
  2446.    * When a preference is toggled that affects whether an item is usable or not
  2447.    * we must app-enable or app-disable the item based on the new settings.
  2448.    */
  2449.   _updateAppDisabledState: function() {
  2450.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2451.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2452.     var ds = this.datasource;
  2453.  
  2454.     // Enumerate all items
  2455.     var ctr = getContainer(ds, ds._itemRoot);
  2456.     var elements = ctr.GetElements();
  2457.     while (elements.hasMoreElements()) {
  2458.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  2459.  
  2460.       // App disable or enable items as necessary
  2461.       // _appEnableItem and _appDisableItem will do nothing if the item is already
  2462.       // in the right state.
  2463.       id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  2464.       if (this._isUsableItem(id))
  2465.         this._appEnableItem(id);
  2466.       else
  2467.         this._appDisableItem(id);
  2468.     }
  2469.   },
  2470.  
  2471.   /**
  2472.    * Initialize the system after a profile has been selected.
  2473.    */
  2474.   _profileSelected: function() {
  2475.     // Tell the Chrome Registry which Skin to select
  2476.     try {
  2477.       if (gPref.getBoolPref(PREF_DSS_SWITCHPENDING)) {
  2478.         var toSelect = gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  2479.         gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, toSelect);
  2480.         gPref.clearUserPref(PREF_DSS_SWITCHPENDING);
  2481.         gPref.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
  2482.       }
  2483.     }
  2484.     catch (e) {
  2485.     }
  2486.  
  2487.     if ("nsICrashReporter" in Ci && gApp instanceof Ci.nsICrashReporter) {
  2488.       // Annotate the crash report with the list of add-ons
  2489.       try {
  2490.         try {
  2491.           gApp.annotateCrashReport("Add-ons", gPref.getCharPref(PREF_EM_ENABLED_ITEMS));
  2492.         } catch (e) { }
  2493.         gApp.annotateCrashReport("Theme", gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN));
  2494.       }
  2495.       catch (ex) {
  2496.         // This will fail in unnofficial builds, ignorable error
  2497.       }
  2498.     }
  2499.  
  2500.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2501.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2502.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2503.     gPref.addObserver("extensions.", this, false);
  2504.     gPref.addObserver(PREF_MATCH_OS_LOCALE, this, false);
  2505.     gPref.addObserver(PREF_SELECTED_LOCALE, this, false);
  2506.     this._updateLocale();
  2507.   },
  2508.  
  2509.   /**
  2510.    * Notify user that there are new addons updates
  2511.    */
  2512.   _showUpdatesWindow: function() {
  2513.     if (!getPref("getBoolPref", PREF_UPDATE_NOTIFYUSER, false))
  2514.       return;
  2515.  
  2516.     const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  2517.     const EMFEATURES = "chrome,centerscreen,extra-chrome,dialog,resizable,modal";
  2518.  
  2519.     var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2520.              getService(Ci.nsIWindowWatcher);
  2521.     var param = Cc["@mozilla.org/supports-array;1"].
  2522.                 createInstance(Ci.nsISupportsArray);
  2523.     var arg = Cc["@mozilla.org/supports-string;1"].
  2524.               createInstance(Ci.nsISupportsString);
  2525.     arg.data = "updates-only";
  2526.     param.AppendElement(arg);
  2527.     ww.openWindow(null, EMURL, null, EMFEATURES, param);
  2528.   },
  2529.  
  2530.   /**
  2531.    * Clean up on application shutdown to avoid leaks.
  2532.    */
  2533.   _shutdown: function() {
  2534.     if (!gAllowFlush) {
  2535.       // Something went wrong and there are potentially flushes pending.
  2536.       ERROR("Reached _shutdown and without clearing any pending flushes");
  2537.       try {
  2538.         gAllowFlush = true;
  2539.         if (gManifestNeedsFlush) {
  2540.           gManifestNeedsFlush = false;
  2541.           this._updateManifests(false);
  2542.         }
  2543.         if (gDSNeedsFlush) {
  2544.           gDSNeedsFlush = false;
  2545.           this.datasource.Flush();
  2546.         }
  2547.       }
  2548.       catch (e) {
  2549.         ERROR("Error flushing caches: " + e);
  2550.       }
  2551.     }
  2552.  
  2553.     gOS.removeObserver(this, "xpcom-shutdown");
  2554.  
  2555.     // Release strongly held services.
  2556.     gOS = null;
  2557.     if (this._ptr && gRDF) {
  2558.       gRDF.UnregisterDataSource(this._ptr);
  2559.       this._ptr = null;
  2560.     }
  2561.     gRDF = null;
  2562.     if (gPref) {
  2563.       gPref.removeObserver("extensions.", this);
  2564.       gPref.removeObserver(PREF_MATCH_OS_LOCALE, this);
  2565.       gPref.removeObserver(PREF_SELECTED_LOCALE, this);
  2566.     }
  2567.     gPref = null;
  2568.     gConsole = null;
  2569.     gVersionChecker = null;
  2570.     gInstallManifestRoot = null;
  2571.     gApp = null;
  2572.   },
  2573.  
  2574.   /**
  2575.    * Check for presence of critical Extension system files. If any is missing,
  2576.    * delete the others and signal that the system needs to rebuild them all
  2577.    * from scratch.
  2578.    * @returns true if any critical file is missing and the system needs to
  2579.    *          be rebuilt, false otherwise.
  2580.    */
  2581.   _ensureDatasetIntegrity: function () {
  2582.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  2583.     var extensionsINI = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2584.     var extensionsCache = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2585.  
  2586.     var dsExists = extensionsDS.exists();
  2587.     var iniExists = extensionsINI.exists();
  2588.     var cacheExists = extensionsCache.exists();
  2589.  
  2590.     if (dsExists && iniExists && cacheExists)
  2591.       return false;
  2592.  
  2593.     // If any of the files are missing, remove the .ini file
  2594.     if (iniExists)
  2595.       extensionsINI.remove(false);
  2596.  
  2597.     // If the extensions datasource is missing remove the .cache file if it exists
  2598.     if (!dsExists && cacheExists)
  2599.       extensionsCache.remove(false);
  2600.  
  2601.     return true;
  2602.   },
  2603.  
  2604.   /**
  2605.    * See nsIExtensionManager.idl
  2606.    */
  2607.   start: function(commandLine) {
  2608.     var isDirty = false;
  2609.     var forceAutoReg = false;
  2610.  
  2611.     // Somehow the component list went away, and for that reason the new one
  2612.     // generated by this function is going to result in a different compreg.
  2613.     // We must force a restart.
  2614.     var componentList = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2615.     if (!componentList.exists())
  2616.       forceAutoReg = true;
  2617.  
  2618.     // Check for missing manifests - e.g. missing extensions.ini, missing
  2619.     // extensions.cache, extensions.rdf etc. If any of these files
  2620.     // is missing then we are in some kind of weird or initial state and need
  2621.     // to force a regeneration.
  2622.     if (this._ensureDatasetIntegrity())
  2623.       isDirty = true;
  2624.  
  2625.     // Block attempts to flush for the entire startup
  2626.     gAllowFlush = false;
  2627.  
  2628.     // Configure any items that are being installed, uninstalled or upgraded
  2629.     // by being added, removed or modified by another process. We must do this
  2630.     // on every startup since there is no way we can tell if this has happened
  2631.     // or not!
  2632.     if (this._checkForFileChanges())
  2633.       isDirty = true;
  2634.  
  2635.     this._showUpdatesWindow();
  2636.  
  2637.     if (PendingOperations.size != 0)
  2638.       isDirty = true;
  2639.  
  2640.     var needsRestart = false;
  2641.     // Extension Changes
  2642.     if (isDirty) {
  2643.       needsRestart = this._finishOperations();
  2644.  
  2645.       if (forceAutoReg) {
  2646.         this._extensionListChanged = true;
  2647.         needsRestart = true;
  2648.       }
  2649.     }
  2650.  
  2651.     // Resume flushing and perform a flush for anything that was deferred
  2652.     try {
  2653.       gAllowFlush = true;
  2654.       if (gManifestNeedsFlush) {
  2655.         gManifestNeedsFlush = false;
  2656.         this._updateManifests(false);
  2657.       }
  2658.       if (gDSNeedsFlush) {
  2659.         gDSNeedsFlush = false;
  2660.         this.datasource.Flush();
  2661.       }
  2662.     }
  2663.     catch (e) {
  2664.       ERROR("Error flushing caches: " + e);
  2665.     }
  2666.  
  2667.     if (!needsRestart)
  2668.       this._startTimers();
  2669.  
  2670.     return needsRestart;
  2671.   },
  2672.  
  2673.   /**
  2674.    * Begins all background update check timers
  2675.    */
  2676.   _startTimers: function() {
  2677.     // Register a background update check timer
  2678.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  2679.              getService(Ci.nsIUpdateTimerManager);
  2680.     var interval = getPref("getIntPref", PREF_EM_UPDATE_INTERVAL, 86400);
  2681.     tm.registerTimer("addon-background-update-timer", this, interval);
  2682.   },
  2683.  
  2684.   /**
  2685.    * Notified when a timer fires
  2686.    * @param   timer
  2687.    *          The timer that fired
  2688.    */
  2689.   notify: function(timer) {
  2690.     if (!getPref("getBoolPref", PREF_EM_UPDATE_ENABLED, true))
  2691.       return;
  2692.  
  2693.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  2694.  
  2695.     var updater = new ExtensionItemUpdater(this);
  2696.     updater.checkForUpdates(items, items.length,
  2697.                             Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION,
  2698.                             new BackgroundUpdateCheckListener(this.datasource));
  2699.   },
  2700.  
  2701.   /**
  2702.    * See nsIExtensionManager.idl
  2703.    */
  2704.   handleCommandLineArgs: function(commandLine) {
  2705.     try {
  2706.       var globalExtension = commandLine.handleFlagWithParam("install-global-extension", false);
  2707.       if (globalExtension) {
  2708.         var file = commandLine.resolveFile(globalExtension);
  2709.         this._installGlobalItem(file);
  2710.       }
  2711.       var globalTheme = commandLine.handleFlagWithParam("install-global-theme", false);
  2712.       if (globalTheme) {
  2713.         file = commandLine.resolveFile(globalTheme);
  2714.         this._installGlobalItem(file);
  2715.       }
  2716.     }
  2717.     catch (e) {
  2718.       ERROR("ExtensionManager:handleCommandLineArgs - failure, catching exception - lineno: " +
  2719.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  2720.     }
  2721.     commandLine.preventDefault = true;
  2722.   },
  2723.  
  2724.   /**
  2725.    * Installs an XPI/JAR file into the KEY_APP_GLOBAL install location.
  2726.    * @param   file
  2727.    *          The XPI/JAR file to extract
  2728.    */
  2729.   _installGlobalItem: function(file) {
  2730.     if (!file || !file.exists())
  2731.       throw new Error("Unable to find the file specified on the command line!");
  2732. //@line 2871 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  2733.     var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2734.     if (!installManifestFile.exists())
  2735.       throw new Error("The package is missing an install manifest!");
  2736.     var installManifest = getInstallManifest(installManifestFile);
  2737.     installManifestFile.remove(false);
  2738.     var installData = this._getInstallData(installManifest);
  2739.     var installer = new Installer(installManifest, installData.id,
  2740.                                   InstallLocations.get(KEY_APP_GLOBAL),
  2741.                                   installData.type);
  2742.     installer._installExtensionFiles(file);
  2743.     if (installData.type == Ci.nsIUpdateItem.TYPE_THEME)
  2744.       installer.upgradeThemeChrome();
  2745.     else
  2746.       installer.upgradeExtensionChrome();
  2747.   },
  2748.  
  2749.   /**
  2750.    * Check to see if a file is a XPI/JAR file that the user dropped into this
  2751.    * Install Location. (i.e. a XPI that is not a staged XPI from an install
  2752.    * transaction that is currently in operation).
  2753.    * @param   file
  2754.    *          The XPI/JAR file to configure
  2755.    * @param   location
  2756.    *          The Install Location where this file was found.
  2757.    * @returns A nsIUpdateItem representing the dropped XPI if this file was a
  2758.    *          XPI/JAR that needs installation, null otherwise.
  2759.    */
  2760.   _getItemForDroppedFile: function(file, location) {
  2761.     if (fileIsItemPackage(file)) {
  2762.       // We know nothing about this item, it is not something we've
  2763.       // staged in preparation for finalization, so assume it's something
  2764.       // the user dropped in.
  2765.       LOG("A Item Package appeared at: " + file.path + " that we know " +
  2766.           "nothing about, assuming it was dropped in by the user and " +
  2767.           "configuring for installation now. Location Key: " + location.name);
  2768.  
  2769.       var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2770.       if (!installManifestFile.exists())
  2771.         return null;
  2772.       var installManifest = getInstallManifest(installManifestFile);
  2773.       installManifestFile.remove(false);
  2774.       var ds = this.datasource;
  2775.       var installData = this._getInstallData(installManifest);
  2776.       var targetAppInfo = ds.getTargetApplicationInfo(installData.id, installManifest);
  2777.       return makeItem(installData.id,
  2778.                       installData.version,
  2779.                       location.name,
  2780.                       targetAppInfo ? targetAppInfo.minVersion : "",
  2781.                       targetAppInfo ? targetAppInfo.maxVersion : "",
  2782.                       getManifestProperty(installManifest, "name"),
  2783.                       "", /* XPI Update URL */
  2784.                       "", /* XPI Update Hash */
  2785.                       getManifestProperty(installManifest, "iconURL"),
  2786.                       getManifestProperty(installManifest, "updateURL"),
  2787.                       getManifestProperty(installManifest, "updateKey"),
  2788.                       installData.type,
  2789.                       targetAppInfo ? targetAppInfo.appID : gApp.ID);
  2790.     }
  2791.     return null;
  2792.   },
  2793.  
  2794.   /**
  2795.    * Configure an item that was installed or upgraded by another process
  2796.    * so that |_finishOperations| can properly complete processing and
  2797.    * registration.
  2798.    * As this is the only point at which we can reliably know the Install
  2799.    * Location of this item, we use this as an opportunity to:
  2800.    * 1. Check that this item is compatible with this Firefox version.
  2801.    * 2. If it is, configure the item by using the supplied callback.
  2802.    *    We do not do any special handling in the case that the item is
  2803.    *    not compatible with this version other than to simply not register
  2804.    *    it and log that fact - there is no "phone home" check for updates.
  2805.    *    It may or may not make sense to do this, but for now we'll just
  2806.    *    not register.
  2807.    * @param   id
  2808.    *          The GUID of the item to validate and configure.
  2809.    * @param   location
  2810.    *          The Install Location where this item is installed.
  2811.    * @param   callback
  2812.    *          The callback that configures the item for installation upon
  2813.    *          successful validation.
  2814.    */
  2815.    installItem: function(id, location, callback) {
  2816.     // As this is the only pint at which we reliably know the installation
  2817.     var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  2818.     if (installRDF.exists()) {
  2819.       LOG("Item Installed/Upgraded at Install Location: " + location.name +
  2820.           " Item ID: " + id + ", attempting to register...");
  2821.       var installManifest = getInstallManifest(installRDF);
  2822.       var installData = this._getInstallData(installManifest);
  2823.       if (installData.error == INSTALLERROR_SUCCESS) {
  2824.         LOG("... success, item is compatible");
  2825.         callback(installManifest, installData.id, location, installData.type);
  2826.       }
  2827.       else if (installData.error == INSTALLERROR_INCOMPATIBLE_VERSION) {
  2828.         LOG("... success, item installed but is not compatible");
  2829.         callback(installManifest, installData.id, location, installData.type);
  2830.         this._appDisableItem(id);
  2831.       }
  2832.       else if (installData.error == INSTALLERROR_INSECURE_UPDATE) {
  2833.         LOG("... success, item installed but does not provide updates securely");
  2834.         callback(installManifest, installData.id, location, installData.type);
  2835.         this._appDisableItem(id);
  2836.       }
  2837.       else if (installData.error == INSTALLERROR_BLOCKLISTED) {
  2838.         LOG("... success, item installed but is blocklisted");
  2839.         callback(installManifest, installData.id, location, installData.type);
  2840.         this._appDisableItem(id);
  2841.       }
  2842.       else {
  2843.         /**
  2844.          * Turns an error code into a message for logging
  2845.          * @param   error
  2846.          *          an Install Error code
  2847.          * @returns A string message to be logged.
  2848.          */
  2849.         function translateErrorMessage(error) {
  2850.           switch (error) {
  2851.           case INSTALLERROR_INVALID_GUID:
  2852.             return "Invalid GUID";
  2853.           case INSTALLERROR_INVALID_VERSION:
  2854.             return "Invalid Version";
  2855.           case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  2856.             return "Incompatible Platform";
  2857.           }
  2858.         }
  2859.         LOG("... failure, item is not compatible, error: " +
  2860.             translateErrorMessage(installData.error));
  2861.  
  2862.         // Add the item to the Startup Cache anyway, so we don't re-detect it
  2863.         // every time the app starts.
  2864.         StartupCache.put(location, id, OP_NONE, true);
  2865.       }
  2866.     }
  2867.   },
  2868.  
  2869.   /**
  2870.    * Check for changes to items that were made independently of the Extension
  2871.    * Manager, e.g. items were added or removed from a Install Location or items
  2872.    * in an Install Location changed.
  2873.    */
  2874.   _checkForFileChanges: function() {
  2875.     var em = this;
  2876.  
  2877.     /**
  2878.      * Determines if an item can be used based on whether or not the install
  2879.      * location of the "item" has an equal or higher priority than the install
  2880.      * location where another version may live.
  2881.      * @param   id
  2882.      *          The GUID of the item being installed.
  2883.      * @param   location
  2884.      *          The location where an item is to be installed.
  2885.      * @returns true if the item can be installed at that location, false
  2886.      *          otherwise.
  2887.      */
  2888.     function canUse(id, location) {
  2889.       for (var locationKey in StartupCache.entries) {
  2890.         if (locationKey != location.name &&
  2891.             id in StartupCache.entries[locationKey]) {
  2892.           if (StartupCache.entries[locationKey][id]) {
  2893.             var oldInstallLocation = InstallLocations.get(locationKey);
  2894.             if (oldInstallLocation.priority <= location.priority)
  2895.               return false;
  2896.           }
  2897.         }
  2898.       }
  2899.       return true;
  2900.     }
  2901.  
  2902.     /**
  2903.       * Gets a Dialog Param Block loaded with a set of strings to initialize the
  2904.       * XPInstall Confirmation Dialog.
  2905.       * @param   strings
  2906.       *          An array of strings
  2907.       * @returns A nsIDialogParamBlock loaded with the strings and dialog state.
  2908.       */
  2909.     function getParamBlock(strings) {
  2910.       var dpb = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  2911.                 createInstance(Ci.nsIDialogParamBlock);
  2912.       // OK and Cancel Buttons
  2913.       dpb.SetInt(0, 2);
  2914.       // Number of Strings
  2915.       dpb.SetInt(1, strings.length);
  2916.       dpb.SetNumberStrings(strings.length);
  2917.       // Add Strings
  2918.       for (var i = 0; i < strings.length; ++i)
  2919.         dpb.SetString(i, strings[i]);
  2920.  
  2921.       var supportsString = Cc["@mozilla.org/supports-string;1"].
  2922.                            createInstance(Ci.nsISupportsString);
  2923.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  2924.       supportsString.data = bundle.GetStringFromName("droppedInWarning");
  2925.       var objs = Cc["@mozilla.org/array;1"].
  2926.                  createInstance(Ci.nsIMutableArray);
  2927.       objs.appendElement(supportsString, false);
  2928.       dpb.objects = objs;
  2929.       return dpb;
  2930.     }
  2931.  
  2932.     /**
  2933.      * Installs a set of files which were dropped into an install location by
  2934.      * the user, only after user confirmation.
  2935.      * @param   droppedInFiles
  2936.      *          An array of JS objects with the following properties:
  2937.      *          "file"      The nsILocalFile where the XPI lives
  2938.      *          "location"  The Install Location where the XPI was found.
  2939.      * @param   xpinstallStrings
  2940.      *          An array of strings used to initialize the XPInstall Confirm
  2941.      *          dialog.
  2942.      */
  2943.     function installDroppedInFiles(droppedInFiles, xpinstallStrings) {
  2944.       if (droppedInFiles.length == 0)
  2945.         return;
  2946.  
  2947.       var dpb = getParamBlock(xpinstallStrings);
  2948.       var ifptr = Cc["@mozilla.org/supports-interface-pointer;1"].
  2949.                   createInstance(Ci.nsISupportsInterfacePointer);
  2950.       ifptr.data = dpb;
  2951.       ifptr.dataIID = Ci.nsIDialogParamBlock;
  2952.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2953.                getService(Ci.nsIWindowWatcher);
  2954.       ww.openWindow(null, URI_XPINSTALL_CONFIRM_DIALOG,
  2955.                     "", "chrome,centerscreen,modal,dialog,titlebar", ifptr);
  2956.       if (!dpb.GetInt(0)) {
  2957.         // User said OK - install items
  2958.         for (var i = 0; i < droppedInFiles.length; ++i) {
  2959.           em.installItemFromFile(droppedInFiles[i].file,
  2960.                                  droppedInFiles[i].location.name);
  2961.           // We are responsible for cleaning up this file
  2962.           droppedInFiles[i].file.remove(false);
  2963.         }
  2964.       }
  2965.       else {
  2966.         for (i = 0; i < droppedInFiles.length; ++i) {
  2967.           // We are responsible for cleaning up this file
  2968.           droppedInFiles[i].file.remove(false);
  2969.         }
  2970.       }
  2971.     }
  2972.  
  2973.     var isDirty = false;
  2974.     var ignoreMTimeChanges = getPref("getBoolPref", PREF_EM_IGNOREMTIMECHANGES,
  2975.                                      false);
  2976.     StartupCache.read();
  2977.  
  2978.     // Array of objects with 'location' and 'id' properties to maybe install.
  2979.     var newItems = [];
  2980.  
  2981.     var droppedInFiles = [];
  2982.     var xpinstallStrings = [];
  2983.  
  2984.     // Enumerate over the install locations from low to high priority.  The
  2985.     // enumeration returned is pre-sorted.
  2986.     var installLocations = this.installLocations;
  2987.     while (installLocations.hasMoreElements()) {
  2988.       var location = installLocations.getNext().QueryInterface(Ci.nsIInstallLocation);
  2989.  
  2990.       // Hash the set of items actually held by the Install Location.
  2991.       var actualItems = { };
  2992.       var entries = location.itemLocations;
  2993.       while (true) {
  2994.         var entry = entries.nextFile;
  2995.         if (!entry)
  2996.           break;
  2997.  
  2998.         // Is this location a valid item? It must be a directory, and contain
  2999.         // an install.rdf manifest:
  3000.         if (entry.isDirectory()) {
  3001.           var installRDF = entry.clone();
  3002.           installRDF.append(FILE_INSTALL_MANIFEST);
  3003.  
  3004.           var id = location.getIDForLocation(entry);
  3005.           if (!id || (!installRDF.exists() &&
  3006.                       !location.itemIsManagedIndependently(id)))
  3007.             continue;
  3008.  
  3009.           actualItems[id] = entry;
  3010.         }
  3011.         else {
  3012.           // Check to see if this file is a XPI/JAR dropped into this dir
  3013.           // by the user, installing it if necessary. We do this here rather
  3014.           // than separately in |_finishOperations| because I don't want to
  3015.           // walk these lists multiple times on every startup.
  3016.           var item = this._getItemForDroppedFile(entry, location);
  3017.           if (item) {
  3018.             droppedInFiles.push({ file: entry, location: location });
  3019.             var prettyName = "";
  3020.             try {
  3021.               var zipReader = getZipReaderForFile(entry);
  3022.               var principal = { };
  3023.               var certPrincipal = zipReader.getCertificatePrincipal(null, principal);
  3024.               // XXXbz This string could be empty.  This needs better
  3025.               // UI to present principal.value.certificate's subject.
  3026.               prettyName = principal.value.prettyName;
  3027.             }
  3028.             catch (e) { }
  3029.             if (zipReader)
  3030.               zipReader.close();
  3031.             xpinstallStrings = xpinstallStrings.concat([item.name,
  3032.                                                         getURLSpecFromFile(entry),
  3033.                                                         item.iconURL,
  3034.                                                         prettyName]);
  3035.             isDirty = true;
  3036.           }
  3037.         }
  3038.       }
  3039.  
  3040.       if (location.name in StartupCache.entries) {
  3041.         // Look for items that have been uninstalled by removing their directory.
  3042.         for (var id in StartupCache.entries[location.name]) {
  3043.           if (!StartupCache.entries[location.name] ||
  3044.               !StartupCache.entries[location.name][id])
  3045.             continue;
  3046.  
  3047.           // Force _finishOperations to run if we have enabled or disabled items.
  3048.           // XXXdarin this should be unnecessary now that we check
  3049.           // PendingOperations.size in start()
  3050.           if (StartupCache.entries[location.name][id].op == OP_NEEDS_ENABLE ||
  3051.               StartupCache.entries[location.name][id].op == OP_NEEDS_DISABLE)
  3052.             isDirty = true;
  3053.  
  3054.           if (!(id in actualItems) &&
  3055.               StartupCache.entries[location.name][id].op != OP_NEEDS_UNINSTALL &&
  3056.               StartupCache.entries[location.name][id].op != OP_NEEDS_INSTALL &&
  3057.               StartupCache.entries[location.name][id].op != OP_NEEDS_UPGRADE) {
  3058.             // We have an entry for this id in the Extensions database, for this
  3059.             // install location, but it no longer exists in the Install Location.
  3060.             // We can infer from this that the item has been removed, so uninstall
  3061.             // it properly.
  3062.             if (canUse(id, location)) {
  3063.               LOG("Item Uninstalled via file removal from: " + StartupCache.entries[location.name][id].descriptor +
  3064.                   " Item ID: " + id + " Location Key: " + location.name + ", uninstalling item.");
  3065.  
  3066.               // Load the Extensions Datasource and force this item into the visible
  3067.               // items list if it is not already. This allows us to handle the case
  3068.               // where there is an entry for an item in the Startup Cache but not
  3069.               // in the extensions.rdf file - in that case the item will not be in
  3070.               // the visible list and calls to |getInstallLocation| will mysteriously
  3071.               // fail.
  3072.               this.datasource.updateVisibleList(id, location.name, false);
  3073.               this.uninstallItem(id);
  3074.               isDirty = true;
  3075.             }
  3076.           }
  3077.           else if (!ignoreMTimeChanges) {
  3078.             // Look for items whose mtime has changed, and as such we can assume
  3079.             // they have been "upgraded".
  3080.             var lf = { path: StartupCache.entries[location.name][id].descriptor };
  3081.             try {
  3082.                lf = getFileFromDescriptor(StartupCache.entries[location.name][id].descriptor, location);
  3083.             }
  3084.             catch (e) { }
  3085.  
  3086.             if (lf.exists && lf.exists()) {
  3087.               var actualMTime = Math.floor(lf.lastModifiedTime / 1000);
  3088.               if (actualMTime != StartupCache.entries[location.name][id].mtime) {
  3089.                 LOG("Item Location path changed: " + lf.path + " Item ID: " +
  3090.                     id + " Location Key: " + location.name + ", attempting to upgrade item...");
  3091.                 if (canUse(id, location)) {
  3092.                   this.installItem(id, location,
  3093.                                    function(installManifest, id, location, type) {
  3094.                                      em._upgradeItem(installManifest, id, location,
  3095.                                                      type);
  3096.                                    });
  3097.                   isDirty = true;
  3098.                 }
  3099.               }
  3100.             }
  3101.             else {
  3102.               isDirty = true;
  3103.               LOG("Install Location returned a missing or malformed item path! " +
  3104.                   "Item Path: " + lf.path + ", Location Key: " + location.name +
  3105.                   " Item ID: " + id);
  3106.               if (canUse(id, location)) {
  3107.                 // Load the Extensions Datasource and force this item into the visible
  3108.                 // items list if it is not already. This allows us to handle the case
  3109.                 // where there is an entry for an item in the Startup Cache but not
  3110.                 // in the extensions.rdf file - in that case the item will not be in
  3111.                 // the visible list and calls to |getInstallLocation| will mysteriously
  3112.                 // fail.
  3113.                 this.datasource.updateVisibleList(id, location.name, false);
  3114.                 this.uninstallItem(id);
  3115.               }
  3116.             }
  3117.           }
  3118.         }
  3119.       }
  3120.  
  3121.       // Look for items that have been installed by appearing in the location.
  3122.       for (var id in actualItems) {
  3123.         if (!(location.name in StartupCache.entries) ||
  3124.             !(id in StartupCache.entries[location.name]) ||
  3125.             !StartupCache.entries[location.name][id]) {
  3126.           // Remember that we've seen this item
  3127.           StartupCache.put(location, id, OP_NONE, true);
  3128.           // Push it on the stack of items to maybe install later
  3129.           newItems.push({location: location, id: id});
  3130.         }
  3131.       }
  3132.     }
  3133.  
  3134.     // Process any newly discovered items.  We do this here instead of in the
  3135.     // previous loop so that we can be sure that we have a fully populated
  3136.     // StartupCache.
  3137.     for (var i = 0; i < newItems.length; ++i) {
  3138.       var id = newItems[i].id;
  3139.       var location = newItems[i].location;
  3140.       if (canUse(id, location)) {
  3141.         LOG("Item Installed via directory addition to Install Location: " +
  3142.             location.name + " Item ID: " + id + ", attempting to register...");
  3143.         this.installItem(id, location,
  3144.                          function(installManifest, id, location, type) {
  3145.                            em._configureForthcomingItem(installManifest, id, location,
  3146.                                                         type);
  3147.                          });
  3148.         // Disable add-ons on install when the InstallDisabled file exists.
  3149.         // This is so Talkback will be disabled on a subset of installs.
  3150.         var installDisabled = location.getItemFile(id, "InstallDisabled");
  3151.         if (installDisabled.exists())
  3152.           em.disableItem(id);
  3153.         isDirty = true;
  3154.       }
  3155.     }
  3156.  
  3157.     // Ask the user if they want to install the dropped items, for security
  3158.     // purposes.
  3159.     installDroppedInFiles(droppedInFiles, xpinstallStrings);
  3160.  
  3161.     return isDirty;
  3162.   },
  3163.  
  3164.   /**
  3165.    * Upgrades contents.rdf files to chrome.manifest files for any existing
  3166.    * Extensions and Themes.
  3167.    * @returns true if actions were performed that require a restart, false
  3168.    *          otherwise.
  3169.    */
  3170.   _upgradeChrome: function() {
  3171.     if (inSafeMode())
  3172.       return false;
  3173.  
  3174.     var checkForNewChrome = false;
  3175.     var ds = this.datasource;
  3176.     // If we have extensions that were installed before the new flat chrome
  3177.     // manifests, and are still valid, we need to manually create the flat
  3178.     // manifest files.
  3179.     var extensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_EXTENSION +
  3180.                                           Ci.nsIUpdateItem.TYPE_LOCALE);
  3181.     for (var i = 0; i < extensions.length; ++i) {
  3182.       var e = extensions[i];
  3183.       var itemLocation = e.location.getItemLocation(e.id);
  3184.       var manifest = itemLocation.clone();
  3185.       manifest.append(FILE_CHROME_MANIFEST);
  3186.       if (!manifest.exists()) {
  3187.         var installRDF = itemLocation.clone();
  3188.         installRDF.append(FILE_INSTALL_MANIFEST);
  3189.         var installLocation = this.getInstallLocation(e.id);
  3190.         if (installLocation && installRDF.exists()) {
  3191.           var itemLocation = installLocation.getItemLocation(e.id);
  3192.           if (itemLocation.exists() && itemLocation.isDirectory()) {
  3193.             var installer = new Installer(ds, e.id, installLocation,
  3194.                                           Ci.nsIUpdateItem.TYPE_EXTENSION);
  3195.             installer.upgradeExtensionChrome();
  3196.           }
  3197.         }
  3198.         else {
  3199.           ds.removeItemMetadata(e.id);
  3200.           ds.removeItemFromContainer(e.id);
  3201.         }
  3202.  
  3203.         checkForNewChrome = true;
  3204.       }
  3205.     }
  3206.  
  3207.     var themes = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  3208.     // If we have themes that were installed before the new flat chrome
  3209.     // manifests, and are still valid, we need to manually create the flat
  3210.     // manifest files.
  3211.     for (i = 0; i < themes.length; ++i) {
  3212.       var item = themes[i];
  3213.       var itemLocation = item.location.getItemLocation(item.id);
  3214.       var manifest = itemLocation.clone();
  3215.       manifest.append(FILE_CHROME_MANIFEST);
  3216.       if (manifest.exists() ||
  3217.           item.id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  3218.         continue;
  3219.  
  3220.       var entries;
  3221.       try {
  3222.         var manifestURI = getURIFromFile(manifest);
  3223.         var chromeDir = itemLocation.clone();
  3224.         chromeDir.append(DIR_CHROME);
  3225.  
  3226.         if (!chromeDir.exists() || !chromeDir.isDirectory()) {
  3227.           ds.removeItemMetadata(item.id);
  3228.           ds.removeItemFromContainer(item.id);
  3229.           continue;
  3230.         }
  3231.  
  3232.         // We're relying on the fact that there is only one JAR file
  3233.         // in the "chrome" directory. This is a hack, but it works.
  3234.         entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3235.         var jarFile = entries.nextFile;
  3236.         if (jarFile) {
  3237.           var jarFileURI = getURIFromFile(jarFile);
  3238.           var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  3239.  
  3240.           // Use the Chrome Registry API to install the theme there
  3241.           var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3242.                    getService(Ci.nsIToolkitChromeRegistry);
  3243.           cr.processContentsManifest(contentsURI, manifestURI, contentsURI, false, true);
  3244.         }
  3245.         entries.close();
  3246.       }
  3247.       catch (e) {
  3248.         ERROR("_upgradeChrome: failed to upgrade contents manifest for " +
  3249.               "theme: " + item.id + ", exception: " + e + "... The theme will be " +
  3250.               "disabled.");
  3251.         this._appDisableItem(item.id);
  3252.       }
  3253.       finally {
  3254.         try {
  3255.           entries.close();
  3256.         }
  3257.         catch (e) {
  3258.         }
  3259.       }
  3260.       checkForNewChrome = true;
  3261.     }
  3262.     return checkForNewChrome;
  3263.   },
  3264.  
  3265.   _checkForUncoveredItem: function(id) {
  3266.     var ds = this.datasource;
  3267.     var oldLocation = this.getInstallLocation(id);
  3268.     var newLocations = [];
  3269.     for (var locationKey in StartupCache.entries) {
  3270.       var location = InstallLocations.get(locationKey);
  3271.       if (id in StartupCache.entries[locationKey] &&
  3272.           location.priority > oldLocation.priority)
  3273.         newLocations.push(location);
  3274.     }
  3275.     newLocations.sort(function(a, b) { return b.priority - a.priority; });
  3276.     if (newLocations.length > 0) {
  3277.       for (var i = 0; i < newLocations.length; ++i) {
  3278.         // Check to see that the item at the location exists
  3279.         var installRDF = newLocations[i].getItemFile(id, FILE_INSTALL_MANIFEST);
  3280.         if (installRDF.exists()) {
  3281.           // Update the visible item cache so that |_finalizeUpgrade| is properly
  3282.           // called from |_finishOperations|
  3283.           var name = newLocations[i].name;
  3284.           ds.updateVisibleList(id, name, true);
  3285.           PendingOperations.addItem(OP_NEEDS_UPGRADE,
  3286.                                     { locationKey: name, id: id });
  3287.           PendingOperations.addItem(OP_NEEDS_INSTALL,
  3288.                                     { locationKey: name, id: id });
  3289.           break;
  3290.         }
  3291.         else {
  3292.           // If no item exists at the location specified, remove this item
  3293.           // from the visible items list and check again.
  3294.           StartupCache.clearEntry(newLocations[i], id);
  3295.           ds.updateVisibleList(id, null, true);
  3296.         }
  3297.       }
  3298.     }
  3299.     else
  3300.       ds.updateVisibleList(id, null, true);
  3301.   },
  3302.  
  3303.   /**
  3304.    * Finish up pending operations - perform upgrades, installs, enables/disables,
  3305.    * uninstalls etc.
  3306.    * @returns true if actions were performed that require a restart, false
  3307.    *          otherwise.
  3308.    */
  3309.   _finishOperations: function() {
  3310.     try {
  3311.       // Stuff has changed, load the Extensions datasource in all its RDFey
  3312.       // glory.
  3313.       var ds = this.datasource;
  3314.       var updatedTargetAppInfos = [];
  3315.  
  3316.       var needsRestart = false;
  3317.       var upgrades = [];
  3318.       var newAddons = [];
  3319.       var addons = getPref("getCharPref", PREF_EM_NEW_ADDONS_LIST, "");
  3320.       if (addons != "")
  3321.         newAddons = addons.split(",");
  3322.       do {
  3323.         // Enable and disable during startup so items that are changed in the
  3324.         // ui can be reset to a no-op.
  3325.         // Look for extensions that need to be enabled.
  3326.         var items = PendingOperations.getOperations(OP_NEEDS_ENABLE);
  3327.         for (var i = items.length - 1; i >= 0; --i) {
  3328.           var id = items[i].id;
  3329.           var installLocation = this.getInstallLocation(id);
  3330.           StartupCache.put(installLocation, id, OP_NONE, true);
  3331.           PendingOperations.clearItem(OP_NEEDS_ENABLE, id);
  3332.           needsRestart = true;
  3333.         }
  3334.         PendingOperations.clearItems(OP_NEEDS_ENABLE);
  3335.  
  3336.         // Look for extensions that need to be disabled.
  3337.         items = PendingOperations.getOperations(OP_NEEDS_DISABLE);
  3338.         for (i = items.length - 1; i >= 0; --i) {
  3339.           id = items[i].id;
  3340.           installLocation = this.getInstallLocation(id);
  3341.           StartupCache.put(installLocation, id, OP_NONE, true);
  3342.           PendingOperations.clearItem(OP_NEEDS_DISABLE, id);
  3343.           needsRestart = true;
  3344.         }
  3345.         PendingOperations.clearItems(OP_NEEDS_DISABLE);
  3346.  
  3347.         // Look for extensions that need to be upgraded. The process here is to
  3348.         // uninstall the old version of the extension first, then install the
  3349.         // new version in its place.
  3350.         items = PendingOperations.getOperations(OP_NEEDS_UPGRADE);
  3351.         for (i = items.length - 1; i >= 0; --i) {
  3352.           id = items[i].id;
  3353.           var newLocation = InstallLocations.get(items[i].locationKey);
  3354.           // check if there is updated app compatibility info
  3355.           var newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3356.           if (newTargetAppInfo)
  3357.             updatedTargetAppInfos.push(newTargetAppInfo);
  3358.           this._finalizeUpgrade(id, newLocation);
  3359.           upgrades.push(id);
  3360.         }
  3361.         PendingOperations.clearItems(OP_NEEDS_UPGRADE);
  3362.  
  3363.         // Install items
  3364.         items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3365.         for (i = items.length - 1; i >= 0; --i) {
  3366.           needsRestart = true;
  3367.           id = items[i].id;
  3368.           // check if there is updated app compatibility info
  3369.           newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3370.           if (newTargetAppInfo)
  3371.             updatedTargetAppInfos.push(newTargetAppInfo);
  3372.           this._finalizeInstall(id, null);
  3373.           if (upgrades.indexOf(id) < 0 && newAddons.indexOf(id) < 0)
  3374.             newAddons.push(id);
  3375.         }
  3376.         PendingOperations.clearItems(OP_NEEDS_INSTALL);
  3377.  
  3378.         // Look for extensions that need to be removed. This MUST be done after
  3379.         // the install operations since extensions to be installed may have to be
  3380.         // uninstalled if there are errors during the installation process!
  3381.         items = PendingOperations.getOperations(OP_NEEDS_UNINSTALL);
  3382.         for (i = items.length - 1; i >= 0; --i) {
  3383.           id = items[i].id;
  3384.           this._finalizeUninstall(id);
  3385.           this._checkForUncoveredItem(id);
  3386.           needsRestart = true;
  3387.           var pos = newAddons.indexOf(id);
  3388.           if (pos >= 0)
  3389.             newAddons.splice(pos, 1);
  3390.         }
  3391.         PendingOperations.clearItems(OP_NEEDS_UNINSTALL);
  3392.  
  3393.         // When there have been operations and all operations have completed.
  3394.         if (PendingOperations.size == 0) {
  3395.           // If there is updated app compatibility info update the datasource.
  3396.           for (i = 0; i < updatedTargetAppInfos.length; ++i)
  3397.             ds.setTargetApplicationInfo(updatedTargetAppInfos[i].id,
  3398.                                         updatedTargetAppInfos[i].targetAppID,
  3399.                                         updatedTargetAppInfos[i].minVersion,
  3400.                                         updatedTargetAppInfos[i].maxVersion,
  3401.                                         null);
  3402.  
  3403.           // Enumerate all items
  3404.           var ctr = getContainer(ds, ds._itemRoot);
  3405.           var elements = ctr.GetElements();
  3406.           while (elements.hasMoreElements()) {
  3407.             var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3408.  
  3409.             // Ensure appDisabled is in the correct state.
  3410.             id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3411.             if (this._isUsableItem(id))
  3412.               ds.setItemProperty(id, EM_R("appDisabled"), null);
  3413.             else
  3414.               ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3415.  
  3416.             // userDisabled is set based on its value being OP_NEEDS_ENABLE or
  3417.             // OP_NEEDS_DISABLE. This allows us to have an item to be enabled
  3418.             // by the app and disabled by the user during a single restart.
  3419.             var value = stringData(ds.GetTarget(itemResource, EM_R("userDisabled"), true));
  3420.             if (value == OP_NEEDS_ENABLE)
  3421.               ds.setItemProperty(id, EM_R("userDisabled"), null);
  3422.             else if (value == OP_NEEDS_DISABLE)
  3423.               ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  3424.           }
  3425.         }
  3426.       }
  3427.       while (PendingOperations.size > 0);
  3428.  
  3429.       // Upgrade contents.rdf files to the new chrome.manifest format for
  3430.       // existing Extensions and Themes
  3431.       if (this._upgradeChrome()) {
  3432.         var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3433.                  getService(Ci.nsIChromeRegistry);
  3434.         cr.checkForNewChrome();
  3435.       }
  3436.  
  3437.       // If no additional restart is required, it implies that there are
  3438.       // no new components that need registering so we can inform the app
  3439.       // not to do any extra startup checking next time round.
  3440.       this._updateManifests(needsRestart);
  3441.  
  3442.       // Remember the list of add-ons that were installed this time around
  3443.       // unless this was a new profile.
  3444.       if (!gFirstRun && newAddons.length > 0)
  3445.         gPref.setCharPref(PREF_EM_NEW_ADDONS_LIST, newAddons.join(","));
  3446.     }
  3447.     catch (e) {
  3448.       ERROR("ExtensionManager:_finishOperations - failure, catching exception - lineno: " +
  3449.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  3450.     }
  3451.     return needsRestart;
  3452.   },
  3453.  
  3454.   /**
  3455.    * Checks to see if there are items that are incompatible with this version
  3456.    * of the application, disables them to prevent incompatibility problems and
  3457.    * invokes the Update Wizard to look for newer versions.
  3458.    * @returns true if there were incompatible items installed and disabled, and
  3459.    *          the application must now be restarted to reinitialize XPCOM,
  3460.    *          false otherwise.
  3461.    */
  3462.   checkForMismatches: function() {
  3463.     // Check to see if the version of the application that is being started
  3464.     // now is the same one that was started last time.
  3465.     var currAppVersion = gApp.version;
  3466.     var lastAppVersion = getPref("getCharPref", PREF_EM_LAST_APP_VERSION, "");
  3467.     if (currAppVersion == lastAppVersion)
  3468.       return false;
  3469.     // With a new profile lastAppVersion doesn't exist yet.
  3470.     if (!lastAppVersion) {
  3471.       gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3472.       return false;
  3473.     }
  3474.  
  3475.     // Block attempts to flush for the entire startup
  3476.     gAllowFlush = false;
  3477.  
  3478.     // Version mismatch, we have to load the extensions datasource and do
  3479.     // version checking. Time hit here doesn't matter since this doesn't happen
  3480.     // all that often.
  3481.     this._upgradeFromV10();
  3482.  
  3483.     // Make the extensions datasource consistent if it isn't already.
  3484.     var isDirty = false;
  3485.     if (this._ensureDatasetIntegrity())
  3486.       isDirty = true;
  3487.  
  3488.     if (this._checkForFileChanges())
  3489.       isDirty = true;
  3490.  
  3491.     if (PendingOperations.size != 0)
  3492.       isDirty = true;
  3493.  
  3494.     if (isDirty)
  3495.       this._finishOperations();
  3496.  
  3497.     var ds = this.datasource;
  3498.     // During app upgrade cleanup invalid entries in the extensions datasource.
  3499.     ds.beginUpdateBatch();
  3500.     var allResources = ds.GetAllResources();
  3501.     while (allResources.hasMoreElements()) {
  3502.       var res = allResources.getNext().QueryInterface(Ci.nsIRDFResource);
  3503.       if (ds.GetTarget(res, EM_R("downloadURL"), true) ||
  3504.           (!ds.GetTarget(res, EM_R("installLocation"), true) &&
  3505.           stringData(ds.GetTarget(res, EM_R("appDisabled"), true)) == "true"))
  3506.         ds.removeDownload(res.Value);
  3507.     }
  3508.     ds.endUpdateBatch();
  3509.  
  3510.     var badItems = [];
  3511.     var allAppManaged = true;
  3512.     var ctr = getContainer(ds, ds._itemRoot);
  3513.     var elements = ctr.GetElements();
  3514.     while (elements.hasMoreElements()) {
  3515.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3516.       var id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3517.       var location = this.getInstallLocation(id);
  3518.       if (!location) {
  3519.         // Item was in an unknown install location
  3520.         badItems.push(id);
  3521.         continue;
  3522.       }
  3523.  
  3524.       if (ds.getItemProperty(id, "appManaged") == "true") {
  3525.         // Force an update of the metadata for appManaged extensions since the
  3526.         // last modified time is not updated for directories on FAT / FAT32
  3527.         // filesystems when software update applies a new version of the app.
  3528.         if (location.name == KEY_APP_GLOBAL) {
  3529.           var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3530.           if (installRDF.exists()) {
  3531.             var metadataDS = getInstallManifest(installRDF);
  3532.             ds.addItemMetadata(id, metadataDS, location);
  3533.             ds.updateProperty(id, "compatible");
  3534.           }
  3535.         }
  3536.       }
  3537.       else if (allAppManaged)
  3538.         allAppManaged = false;
  3539.  
  3540.       var properties = {
  3541.         availableUpdateURL: null,
  3542.         availableUpdateVersion: null
  3543.       };
  3544.  
  3545.       if (ds.getItemProperty(id, "providesUpdatesSecurely") == "false") {
  3546.         /* It's possible the previous version did not understand updateKeys so
  3547.          * check if we can import one for this addon from it's manifest. */
  3548.         installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3549.         if (installRDF.exists()) {
  3550.           metadataDS = getInstallManifest(installRDF);
  3551.           var literal = metadataDS.GetTarget(gInstallManifestRoot, EM_R("updateKey"), true);
  3552.           if (literal && literal instanceof Ci.nsIRDFLiteral)
  3553.             ds.setItemProperty(id, EM_R("updateKey"), literal);
  3554.         }
  3555.       }
  3556.  
  3557.       // appDisabled is determined by an item being compatible, using secure
  3558.       // updates, satisfying its dependencies, and not being blocklisted
  3559.       if (this._isUsableItem(id)) {
  3560.         if (ds.getItemProperty(id, "appDisabled"))
  3561.           properties.appDisabled = null;
  3562.       }
  3563.       else if (!ds.getItemProperty(id, "appDisabled")) {
  3564.         properties.appDisabled = EM_L("true");
  3565.       }
  3566.  
  3567.       ds.setItemProperties(id, properties);
  3568.     }
  3569.  
  3570.     // Must clean up outside of the loop. Modifying the container while
  3571.     // iterating its contents is bad.
  3572.     for (var i = 0; i < badItems.length; i++) {
  3573.       id = badItems[i];
  3574.       LOG("Item " + id + " was installed in an unknown location, removing.");
  3575.       var disabled = ds.getItemProperty(id, "userDisabled") == "true";
  3576.       // Clean up the datasource
  3577.       ds.removeCorruptItem(id);
  3578.       // Check for any unhidden items.
  3579.       var entries = StartupCache.findEntries(id);
  3580.       if (entries.length > 0) {
  3581.         var newLocation = InstallLocations.get(entries[0].location);
  3582.         for (var j = 1; j < entries.length; j++) {
  3583.           location = InstallLocations.get(entries[j].location);
  3584.           if (newLocation.priority < location.priority)
  3585.             newLocation = location;
  3586.         }
  3587.         LOG("Activating item " + id + " in " + newLocation.name);
  3588.         var em = this;
  3589.         this.installItem(id, newLocation,
  3590.                          function(installManifest, id, location, type) {
  3591.                            em._configureForthcomingItem(installManifest, id, location,
  3592.                                                         type);
  3593.                          });
  3594.         if (disabled)
  3595.           em.disableItem(id);
  3596.       }
  3597.     }
  3598.  
  3599.     // Update the manifests to reflect the items that were disabled / enabled.
  3600.     this._updateManifests(true);
  3601.  
  3602.     // Always check for compatibility updates when upgrading if we have add-ons
  3603.     // that aren't managed by the application.
  3604.     if (!allAppManaged)
  3605.       this._showMismatchWindow();
  3606.  
  3607.     // Finish any pending upgrades from the compatibility update to avoid an
  3608.     // additional restart.
  3609.     if (PendingOperations.size != 0)
  3610.       this._finishOperations();
  3611.  
  3612.     // Update the last app version so we don't do this again with this version.
  3613.     gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3614.  
  3615.     // Prevent extension update dialog from showing
  3616.     gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  3617.  
  3618.     // Re-enable flushing and flush anything that was deferred
  3619.     try {
  3620.       gAllowFlush = true;
  3621.       if (gManifestNeedsFlush) {
  3622.         gManifestNeedsFlush = false;
  3623.         this._updateManifests(false);
  3624.       }
  3625.       if (gDSNeedsFlush) {
  3626.         gDSNeedsFlush = false;
  3627.         this.datasource.Flush();
  3628.       }
  3629.     }
  3630.     catch (e) {
  3631.       ERROR("Error flushing caches: " + e);
  3632.     }
  3633.  
  3634.     return true;
  3635.   },
  3636.  
  3637.   /**
  3638.    * Shows the "Compatibility Updates" UI
  3639.    */
  3640.   _showMismatchWindow: function(items) {
  3641.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  3642.              getService(Ci.nsIWindowMediator);
  3643.     var wizard = wm.getMostRecentWindow("Update:Wizard");
  3644.     if (wizard)
  3645.       wizard.focus();
  3646.     else {
  3647.       var features = "chrome,centerscreen,dialog,titlebar,modal";
  3648.       // This *must* be modal so as not to break startup! This code is invoked before
  3649.       // the main event loop is initiated (via checkForMismatches).
  3650.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3651.                getService(Ci.nsIWindowWatcher);
  3652.       ww.openWindow(null, URI_EXTENSION_UPDATE_DIALOG, "", features, null);
  3653.     }
  3654.   },
  3655.  
  3656.   /*
  3657.    * Catch all for facilitating a version 1.0 profile upgrade.
  3658.    * 1) removes the abandoned default theme directory from the profile.
  3659.    * 2) prepares themes installed with version 1.0 for installation.
  3660.    * 3) initiates an install to populate the new extensions datasource.
  3661.    * 4) migrates the disabled attribute from the old datasource.
  3662.    * 5) migrates the app compatibility info from the old datasource.
  3663.    */
  3664.   _upgradeFromV10: function() {
  3665.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  3666.     var dsExists = extensionsDS.exists();
  3667.     // Toolkiit 1.7 profiles (Firefox 1.0, Thunderbird 1.0, etc.) have a default
  3668.     // theme directory in the profile's extensions directory that will be
  3669.     // disabled due to having a maxVersion that is incompatible with the
  3670.     // toolkit 1.8 release of the app.
  3671.     var profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3672.                                              stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)]);
  3673.     if (profileDefaultTheme && profileDefaultTheme.exists()) {
  3674.       removeDirRecursive(profileDefaultTheme);
  3675.       // Sunbird 0.3a1 didn't move the default theme into the app's extensions
  3676.       // directory and we can't install it while uninstalling the one in the
  3677.       // profile directory. If we have a toolkit 1.8 extensions datasource and
  3678.       // a profile default theme deleting the toolkit 1.8 extensions datasource
  3679.       // will fix this problem when the datasource is re-created.
  3680.       if (dsExists)
  3681.         extensionsDS.remove(false);
  3682.     }
  3683.  
  3684.     // return early if the toolkit 1.7 extensions datasource file doesn't exist.
  3685.     var oldExtensionsFile = getFile(KEY_PROFILEDIR, [DIR_EXTENSIONS, "Extensions.rdf"]);
  3686.     if (!oldExtensionsFile.exists())
  3687.       return;
  3688.  
  3689.     // Sunbird 0.2 used a different GUID for the default theme
  3690.     profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3691.                                          "{8af2d0a7-e394-4de2-ae55-2dae532a7a9b}"]);
  3692.     if (profileDefaultTheme && profileDefaultTheme.exists())
  3693.       removeDirRecursive(profileDefaultTheme);
  3694.  
  3695.     // Firefox 0.9 profiles may have DOMi 1.0 with just an install.rdf
  3696.     var profileDOMi = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3697.                                      "{641d8d09-7dda-4850-8228-ac0ab65e2ac9}"]);
  3698.     if (profileDOMi && profileDOMi.exists())
  3699.       removeDirRecursive(profileDOMi);
  3700.  
  3701.     // return early to avoid migrating data twice if we already have a
  3702.     // toolkit 1.8 extension datasource.
  3703.     if (dsExists)
  3704.       return;
  3705.  
  3706.     // Prepare themes for installation
  3707.     // Only enumerate directories in the app-profile and app-global locations.
  3708.     var locations = [KEY_APP_PROFILE, KEY_APP_GLOBAL];
  3709.     for (var i = 0; i < locations.length; ++i) {
  3710.       var location = InstallLocations.get(locations[i]);
  3711.       if (!location.canAccess)
  3712.         continue;
  3713.  
  3714.       var entries = location.itemLocations;
  3715.       var entry;
  3716.       while ((entry = entries.nextFile)) {
  3717.         var installRDF = entry.clone();
  3718.         installRDF.append(FILE_INSTALL_MANIFEST);
  3719.  
  3720.         var chromeDir = entry.clone();
  3721.         chromeDir.append(DIR_CHROME);
  3722.  
  3723.         // It must be a directory without an install.rdf and it must contain
  3724.         // a chrome directory
  3725.         if (!entry.isDirectory() || installRDF.exists() || !chromeDir.exists())
  3726.           continue;
  3727.  
  3728.         var chromeEntries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3729.         if (!chromeEntries.hasMoreElements())
  3730.           continue;
  3731.  
  3732.         // We're relying on the fact that there is only one JAR file
  3733.         // in the "chrome" directory. This is a hack, but it works.
  3734.         var jarFile = chromeEntries.nextFile;
  3735.         if (jarFile.isDirectory())
  3736.           continue;
  3737.         var id = location.getIDForLocation(entry);
  3738.  
  3739.         try {
  3740.           var zipReader = getZipReaderForFile(jarFile);
  3741.           zipReader.extract(FILE_INSTALL_MANIFEST, installRDF);
  3742.  
  3743.           var contentsManifestFile = location.getItemFile(id, FILE_CONTENTS_MANIFEST);
  3744.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  3745.  
  3746.           var rootFiles = ["preview.png", "icon.png"];
  3747.           for (var i = 0; i < rootFiles.length; ++i) {
  3748.             try {
  3749.               var target = location.getItemFile(id, rootFiles[i]);
  3750.               zipReader.extract(rootFiles[i], target);
  3751.             }
  3752.             catch (e) {
  3753.             }
  3754.           }
  3755.           zipReader.close();
  3756.         }
  3757.         catch (e) {
  3758.           ERROR("ExtensionManager:_upgradeFromV10 - failed to extract theme files\r\n" +
  3759.                 "Exception: " + e);
  3760.         }
  3761.       }
  3762.     }
  3763.  
  3764.     // When upgrading from a version 1.0 profile we need to populate the
  3765.     // extensions datasource with all items before checking for incompatible
  3766.     // items since the datasource hasn't been created yet.
  3767.     var itemsToCheck = [];
  3768.     if (this._checkForFileChanges()) {
  3769.       // Create a list of all items that are to be installed so we can migrate
  3770.       // these items's settings to the new datasource.
  3771.       var items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3772.       for (i = items.length - 1; i >= 0; --i) {
  3773.         if (items[i].locationKey == KEY_APP_PROFILE ||
  3774.             items[i].locationKey == KEY_APP_GLOBAL)
  3775.           itemsToCheck.push(items[i].id);
  3776.       }
  3777.       this._finishOperations();
  3778.     }
  3779.  
  3780.     // If there are no items to migrate settings for return early.
  3781.     if (itemsToCheck.length == 0)
  3782.       return;
  3783.  
  3784.     var fileURL = getURLSpecFromFile(oldExtensionsFile);
  3785.     var oldExtensionsDS = gRDF.GetDataSourceBlocking(fileURL);
  3786.     var versionChecker = getVersionChecker();
  3787.     var ds = this.datasource;
  3788.     var currAppVersion = gApp.version;
  3789.     var currAppID = gApp.ID;
  3790.     for (var i = 0; i < itemsToCheck.length; ++i) {
  3791.       var item = ds.getItemForID(itemsToCheck[i]);
  3792.       var oldPrefix = (item.type == Ci.nsIUpdateItem.TYPE_EXTENSION) ? PREFIX_EXTENSION : PREFIX_THEME;
  3793.       var oldRes = gRDF.GetResource(oldPrefix + item.id);
  3794.       // Disable the item if it was disabled in the version 1.0 extensions
  3795.       // datasource.
  3796.       if (oldExtensionsDS.GetTarget(oldRes, EM_R("disabled"), true))
  3797.         ds.setItemProperty(item.id, EM_R("userDisabled"), EM_L("true"));
  3798.  
  3799.       // app enable all items. If it is incompatible it will be app disabled
  3800.       // later on.
  3801.       ds.setItemProperty(item.id, EM_R("appDisabled"), null);
  3802.  
  3803.       // if the item is already compatible don't attempt to migrate the
  3804.       // item's compatibility info
  3805.       var newRes = getResourceForID(itemsToCheck[i]);
  3806.       if (ds.isCompatible(ds, newRes))
  3807.         continue;
  3808.  
  3809.       var updatedMinVersion = null;
  3810.       var updatedMaxVersion = null;
  3811.       var targetApps = oldExtensionsDS.GetTargets(oldRes, EM_R("targetApplication"), true);
  3812.       while (targetApps.hasMoreElements()) {
  3813.         var targetApp = targetApps.getNext();
  3814.         if (targetApp instanceof Ci.nsIRDFResource) {
  3815.           try {
  3816.             var foundAppID = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("id"), true));
  3817.             // Different target application?  (Note:  v1.0 didn't support toolkit app ID)
  3818.             if (foundAppID != currAppID)
  3819.               continue;
  3820.  
  3821.             updatedMinVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("minVersion"), true));
  3822.             updatedMaxVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("maxVersion"), true));
  3823.  
  3824.             // Only set the target app info if the extension's target app info
  3825.             // in the version 1.0 extensions datasource makes it compatible
  3826.             if (versionChecker.compare(currAppVersion, updatedMinVersion) >= 0 &&
  3827.                 versionChecker.compare(currAppVersion, updatedMaxVersion) <= 0)
  3828.               ds.setTargetApplicationInfo(item.id, foundAppID, updatedMinVersion,
  3829.                                           updatedMaxVersion, null);
  3830.  
  3831.             break;
  3832.           }
  3833.           catch (e) {
  3834.           }
  3835.         }
  3836.       }
  3837.     }
  3838.   },
  3839.  
  3840.   /**
  3841.    * Write the Extensions List and the Startup Cache
  3842.    * @param   needsRestart
  3843.    *          true if the application needs to restart again, false otherwise.
  3844.    */
  3845.   _updateManifests: function(needsRestart) {
  3846.     // During startup we block flushing until the startup operations are all
  3847.     // complete to reduce file accesses that can trigger bug 431065
  3848.     if (gAllowFlush) {
  3849.       // Write the Startup Cache (All Items, visible or not)
  3850.       StartupCache.write();
  3851.       // Write the Extensions Locations Manifest (Visible, enabled items)
  3852.       this._updateExtensionsManifest();
  3853.     }
  3854.     else {
  3855.       gManifestNeedsFlush = true;
  3856.     }
  3857.  
  3858.     // Notify nsAppRunner to update the compatibility manifest on next startup
  3859.     this._extensionListChanged = needsRestart;
  3860.   },
  3861.  
  3862.   /**
  3863.    * Get a list of items that are currently "active" (turned on) of a specific
  3864.    * type
  3865.    * @param   type
  3866.    *          The nsIUpdateItem type to return a list of items of
  3867.    * @returns An array of active items of the specified type.
  3868.    */
  3869.   _getActiveItems: function(type) {
  3870.     var allItems = this.getItemList(type, { });
  3871.     var activeItems = [];
  3872.     var ds = this.datasource;
  3873.     for (var i = 0; i < allItems.length; ++i) {
  3874.       var item = allItems[i];
  3875.  
  3876.       var installLocation = this.getInstallLocation(item.id);
  3877.       // An entry with an invalid install location is not active.
  3878.       if (!installLocation)
  3879.         continue;
  3880.       // An item entry is valid only if it is not disabled, not about to
  3881.       // be disabled, and not about to be uninstalled.
  3882.       if (installLocation.name in StartupCache.entries &&
  3883.           item.id in StartupCache.entries[installLocation.name] &&
  3884.           StartupCache.entries[installLocation.name][item.id]) {
  3885.         var op = StartupCache.entries[installLocation.name][item.id].op;
  3886.         if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE ||
  3887.             op == OP_NEEDS_UNINSTALL || op == OP_NEEDS_DISABLE)
  3888.           continue;
  3889.       }
  3890.       // Suppress items that have been disabled by the user or the app.
  3891.       if (ds.getItemProperty(item.id, "isDisabled") != "true")
  3892.         activeItems.push({ id: item.id, version: item.version,
  3893.                            location: installLocation });
  3894.     }
  3895.  
  3896.     return activeItems;
  3897.   },
  3898.  
  3899.   /**
  3900.    * Write the Extensions List
  3901.    */
  3902.   _updateExtensionsManifest: function() {
  3903.     // When an operation is performed that requires a component re-registration
  3904.     // (extension enabled/disabled, installed, uninstalled), we must write the
  3905.     // set of paths where extensions live so that the startup system can determine
  3906.     // where additional components, preferences, chrome manifests etc live.
  3907.     //
  3908.     // To do this we obtain a list of active extensions and themes and write
  3909.     // these to the extensions.ini file in the profile directory.
  3910.     var validExtensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_ANY -
  3911.                                                Ci.nsIUpdateItem.TYPE_THEME);
  3912.     var validThemes     = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  3913.  
  3914.     var extensionsLocationsFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  3915.     var fos = openSafeFileOutputStream(extensionsLocationsFile);
  3916.  
  3917.     var enabledItems = [];
  3918.     var extensionSectionHeader = "[ExtensionDirs]\r\n";
  3919.     fos.write(extensionSectionHeader, extensionSectionHeader.length);
  3920.     for (var i = 0; i < validExtensions.length; ++i) {
  3921.       var e = validExtensions[i];
  3922.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  3923.       var descriptor = getAbsoluteDescriptor(itemLocation);
  3924.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  3925.       fos.write(line, line.length);
  3926.       enabledItems.push(e.id + ":" + e.version);
  3927.     }
  3928.  
  3929.     var themeSectionHeader = "[ThemeDirs]\r\n";
  3930.     fos.write(themeSectionHeader, themeSectionHeader.length);
  3931.     for (i = 0; i < validThemes.length; ++i) {
  3932.       var e = validThemes[i];
  3933.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  3934.       var descriptor = getAbsoluteDescriptor(itemLocation);
  3935.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  3936.       fos.write(line, line.length);
  3937.       enabledItems.push(e.id + ":" + e.version);
  3938.     }
  3939.  
  3940.     closeSafeFileOutputStream(fos);
  3941.  
  3942.     // Cache the enabled list for annotating the crash report subsequently
  3943.     gPref.setCharPref(PREF_EM_ENABLED_ITEMS, enabledItems.join(","));
  3944.   },
  3945.  
  3946.   /**
  3947.    * Say whether or not the Extension List has changed (and thus whether or not
  3948.    * the system will have to restart the next time it is started).
  3949.    * @param   val
  3950.    *          true if the Extension List has changed, false otherwise.
  3951.    * @returns |val|
  3952.    */
  3953.   set _extensionListChanged(val) {
  3954.     // When an extension has an operation perform on it (e.g. install, upgrade,
  3955.     // disable, etc.) we are responsible for creating the .autoreg file and
  3956.     // nsAppRunner is responsible for removing it on restart. At some point it
  3957.     // may make sense to be able to cancel a registration but for now we only
  3958.     // create the file.
  3959.     try {
  3960.       var autoregFile = getFile(KEY_PROFILEDIR, [FILE_AUTOREG]);
  3961.       if (val && !autoregFile.exists())
  3962.         autoregFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  3963.     }
  3964.     catch (e) {
  3965.     }
  3966.     return val;
  3967.   },
  3968.  
  3969.   /**
  3970.    * Gathers data about an item specified by the supplied Install Manifest
  3971.    * and determines whether or not it can be installed as-is. It makes this
  3972.    * determination by validating the item's GUID, Version, and determining
  3973.    * if it is compatible with this application.
  3974.    * @param   installManifest
  3975.    *          A nsIRDFDataSource representing the Install Manifest of the
  3976.    *          item to be installed.
  3977.    * @return  A JS Object with the following properties:
  3978.    *          "id"       The GUID of the Item being installed.
  3979.    *          "version"  The Version string of the Item being installed.
  3980.    *          "name"     The Name of the Item being installed.
  3981.    *          "type"     The nsIUpdateItem type of the Item being installed.
  3982.    *          "targetApps" An array of TargetApplication Info Objects
  3983.    *                     with "id", "minVersion" and "maxVersion" properties,
  3984.    *                     representing applications targeted by this item.
  3985.    *          "error"    The result code:
  3986.    *                     INSTALLERROR_SUCCESS
  3987.    *                       no error, item can be installed
  3988.    *                     INSTALLERROR_INVALID_GUID
  3989.    *                       error, GUID is not well-formed
  3990.    *                     INSTALLERROR_INVALID_VERSION
  3991.    *                       error, Version is not well-formed
  3992.    *                     INSTALLERROR_INCOMPATIBLE_VERSION
  3993.    *                       error, item is not compatible with this version
  3994.    *                       of the application.
  3995.    *                     INSTALLERROR_INCOMPATIBLE_PLATFORM
  3996.    *                       error, item is not compatible with the operating
  3997.    *                       system or ABI the application was built for.
  3998.    *                     INSTALLERROR_INSECURE_UPDATE
  3999.    *                       error, item has no secure method of providing updates
  4000.    *                     INSTALLERROR_BLOCKLISTED
  4001.    *                       error, item is blocklisted
  4002.    */
  4003.   _getInstallData: function(installManifest) {
  4004.     var installData = { id          : "",
  4005.                         version     : "",
  4006.                         name        : "",
  4007.                         type        : 0,
  4008.                         error       : INSTALLERROR_SUCCESS,
  4009.                         targetApps  : [],
  4010.                         updateURL   : "",
  4011.                         updateKey   : "",
  4012.                         currentApp  : null };
  4013.  
  4014.     // Fetch properties from the Install Manifest
  4015.     installData.id       = getManifestProperty(installManifest, "id");
  4016.     installData.version  = getManifestProperty(installManifest, "version");
  4017.     installData.name     = getManifestProperty(installManifest, "name");
  4018.     installData.type     = getAddonTypeFromInstallManifest(installManifest);
  4019.     installData.updateURL= getManifestProperty(installManifest, "updateURL");
  4020.     installData.updateKey= getManifestProperty(installManifest, "updateKey");
  4021.  
  4022.     /**
  4023.      * Reads a property off a Target Application resource
  4024.      * @param   resource
  4025.      *          The RDF Resource for a Target Application
  4026.      * @param   property
  4027.      *          The property (less EM_NS) to read
  4028.      * @returns The string literal value of the property.
  4029.      */
  4030.     function readTAProperty(resource, property) {
  4031.       return stringData(installManifest.GetTarget(resource, EM_R(property), true));
  4032.     }
  4033.  
  4034.     var targetApps = installManifest.GetTargets(gInstallManifestRoot,
  4035.                                                 EM_R("targetApplication"),
  4036.                                                 true);
  4037.     while (targetApps.hasMoreElements()) {
  4038.       var targetApp = targetApps.getNext();
  4039.       if (targetApp instanceof Ci.nsIRDFResource) {
  4040.         try {
  4041.           var data = { id        : readTAProperty(targetApp, "id"),
  4042.                        minVersion: readTAProperty(targetApp, "minVersion"),
  4043.                        maxVersion: readTAProperty(targetApp, "maxVersion") };
  4044.           installData.targetApps.push(data);
  4045.           if ((data.id == gApp.ID) ||
  4046.               (data.id == TOOLKIT_ID) && !installData.currentApp)
  4047.             installData.currentApp = data;
  4048.         }
  4049.         catch (e) {
  4050.           continue;
  4051.         }
  4052.       }
  4053.     }
  4054.  
  4055.     // If the item specifies one or more target platforms, make sure our OS/ABI
  4056.     // combination is in the list - otherwise, refuse to install the item.
  4057.     var targetPlatforms = null;
  4058.     try {
  4059.       targetPlatforms = installManifest.GetTargets(gInstallManifestRoot,
  4060.                                                    EM_R("targetPlatform"),
  4061.                                                    true);
  4062.     } catch(e) {
  4063.       // No targetPlatform nodes, continue.
  4064.     }
  4065.     if (targetPlatforms != null && targetPlatforms.hasMoreElements()) {
  4066.       var foundMatchingOS = false;
  4067.       var foundMatchingOSAndABI = false;
  4068.       var requireABICompatibility = false;
  4069.       while (targetPlatforms.hasMoreElements()) {
  4070.         var targetPlatform = stringData(targetPlatforms.getNext());
  4071.         var os = targetPlatform.split("_")[0];
  4072.         var index = targetPlatform.indexOf("_");
  4073.         var abi = index != -1 ? targetPlatform.substr(index + 1) : null;
  4074.         if (os == gOSTarget) {
  4075.           foundMatchingOS = true;
  4076.           // The presence of any ABI part after our OS means ABI is important.
  4077.           if (abi != null) {
  4078.             requireABICompatibility = true;
  4079.             // If we don't know our ABI, we can't be compatible
  4080.             if (abi == gXPCOMABI && abi != UNKNOWN_XPCOM_ABI) {
  4081.               foundMatchingOSAndABI = true;
  4082.               break;
  4083.             }
  4084.           }
  4085.         }
  4086.       }
  4087.       if (!foundMatchingOS || (requireABICompatibility && !foundMatchingOSAndABI)) {
  4088.         installData.error = INSTALLERROR_INCOMPATIBLE_PLATFORM;
  4089.         return installData;
  4090.       }
  4091.     }
  4092.  
  4093.     // Validate the Item ID
  4094.     if (!gIDTest.test(installData.id)) {
  4095.       installData.error = INSTALLERROR_INVALID_GUID;
  4096.       return installData;
  4097.     }
  4098.     
  4099.     // Check that the add-on provides a secure update method.
  4100.     if (gCheckUpdateSecurity &&
  4101.         installData.updateURL &&
  4102.         installData.updateURL.substring(0, 6) != "https:" &&
  4103.         !installData.updateKey) {
  4104.       installData.error = INSTALLERROR_INSECURE_UPDATE;
  4105.       return installData;
  4106.     }
  4107.       
  4108.     // Check that the target application range allows compatibility with the app
  4109.     if (gCheckCompatibility &&
  4110.         !this.datasource.isCompatible(installManifest, gInstallManifestRoot, undefined)) {
  4111.       installData.error = INSTALLERROR_INCOMPATIBLE_VERSION;
  4112.       return installData;
  4113.     }
  4114.     
  4115.     // Check if the item is blocklisted.
  4116.     if (!gBlocklist)
  4117.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  4118.                    getService(Ci.nsIBlocklistService);
  4119.     if (gBlocklist.isAddonBlocklisted(installData.id, installData.version,
  4120.                                       null, null))
  4121.       installData.error = INSTALLERROR_BLOCKLISTED;
  4122.  
  4123.     return installData;
  4124.   },
  4125.  
  4126.   /**
  4127.    * Installs an item from a XPI/JAR file.
  4128.    * This is the main entry point into the Install system from outside code
  4129.    * (e.g. XPInstall).
  4130.    * @param   aXPIFile
  4131.    *          The file to install from.
  4132.    * @param   aInstallLocationKey
  4133.    *          The name of the Install Location where this item should be
  4134.    *          installed.
  4135.    */
  4136.   installItemFromFile: function(xpiFile, installLocationKey) {
  4137.     this.installItemFromFileInternal(xpiFile, installLocationKey, null);
  4138.  
  4139.     // If there are no compatibility checks running and no downloads in
  4140.     // progress then the install operations are complete.
  4141.     if (this._compatibilityCheckCount == 0 && this._transactions.length == 0) {
  4142.       for (var i = 0; i < this._installListeners.length; ++i)
  4143.         this._installListeners[i].onInstallsCompleted();
  4144.     }
  4145.   },
  4146.  
  4147.   /**
  4148.    * Installs an item from a XPI/JAR file.
  4149.    * @param   aXPIFile
  4150.    *          The file to install from.
  4151.    * @param   aInstallLocationKey
  4152.    *          The name of the Install Location where this item should be
  4153.    *          installed.
  4154.    * @param   aInstallManifest
  4155.    *          An updated Install Manifest from the Version Update check.
  4156.    *          Can be null when invoked from callers other than the Version
  4157.    *          Update check.
  4158.    */
  4159.   installItemFromFileInternal: function(aXPIFile, aInstallLocationKey, aInstallManifest) {
  4160.     var em = this;
  4161.     /**
  4162.      * Gets the Install Location for an Item.
  4163.      * @param   itemID
  4164.      *          The GUID of the item to find an Install Location for.
  4165.      * @return  An object implementing nsIInstallLocation which represents the
  4166.      *          location where the specified item should be installed.
  4167.      *          This can be:
  4168.      *          1. an object that corresponds to the location key supplied to
  4169.      *             |installItemFromFileInternal|,
  4170.      *          2. the default install location (the App Profile Extensions Folder)
  4171.      *             if no location key was supplied, or the location key supplied
  4172.      *             was not in the set of registered locations
  4173.      *          3. null, if the location selected by 1 or 2 above does not support
  4174.      *             installs from XPI/JAR files, or that location is not writable
  4175.      *             with the current access privileges.
  4176.      */
  4177.     function getInstallLocation(itemID) {
  4178.       // Here I use "upgrade" to mean "install a different version of an item".
  4179.       var installLocation = em.getInstallLocation(itemID);
  4180.       if (!installLocation) {
  4181.         // This is not an "upgrade", since we don't have any location data for the
  4182.         // extension ID specified - that is, it's not in our database.
  4183.  
  4184.         // Caller supplied a key to a registered location, use that location
  4185.         // for the installation
  4186.         installLocation = InstallLocations.get(aInstallLocationKey);
  4187.         if (installLocation) {
  4188.           // If the specified location does not have a common metadata location
  4189.           // (e.g. extensions have no common root, or other location specified
  4190.           // by the location implementation) - e.g. for a Registry Key enumeration
  4191.           // location - we cannot install or upgrade using a XPI file, probably
  4192.           // because these application types will be handling upgrading themselves.
  4193.           // Just bail.
  4194.           if (!installLocation.location) {
  4195.             LOG("Install Location \"" + installLocation.name + "\" does not support " +
  4196.                 "installation of items from XPI/JAR files. You must manage " +
  4197.                 "installation and update of these items yourself.");
  4198.             installLocation = null;
  4199.           }
  4200.         }
  4201.         else {
  4202.           // In the absence of a preferred install location, just default to
  4203.           // the App-Profile
  4204.           installLocation = InstallLocations.get(KEY_APP_PROFILE);
  4205.         }
  4206.       }
  4207.       else {
  4208.         // This is an "upgrade", but not through the Update System, because the
  4209.         // Update code will not let an extension with an incompatible target
  4210.         // app version range through to this point. This is an "upgrade" in the
  4211.         // sense that the user found a different version of an installed extension
  4212.         // and installed it through the web interface, so we have metadata.
  4213.  
  4214.         // If the location is different, return the preferred location rather than
  4215.         // the location of the currently installed version, because we may be in
  4216.         // the situation where an item is being installed into the global app
  4217.         // dir when there's a version in the profile dir.
  4218.         if (installLocation.name != aInstallLocationKey)
  4219.           installLocation = InstallLocations.get(aInstallLocationKey);
  4220.       }
  4221.       if (!installLocation.canAccess) {
  4222.         LOG("Install Location\"" + installLocation.name + "\" cannot be written " +
  4223.             "to with your access privileges. Installation will not proceed.");
  4224.         installLocation = null;
  4225.       }
  4226.       return installLocation;
  4227.     }
  4228.  
  4229.     /**
  4230.      * Stages a XPI file in the default item location specified by other
  4231.      * applications when they registered with XulRunner if the item's
  4232.      * install manifest specified compatibility with them.
  4233.      */
  4234.     function stageXPIForOtherApps(xpiFile, installData) {
  4235.       for (var i = 0; i < installData.targetApps.length; ++i) {
  4236.         var targetApp = installData.targetApps[i];
  4237.         if (targetApp.id != gApp.ID && targetApp.id != TOOLKIT_ID) {
  4238.         /* XXXben uncomment when this works!
  4239.           var settingsThingy = Cc[].
  4240.                                getService(Ci.nsIXULRunnerSettingsThingy);
  4241.           try {
  4242.             var appPrefix = "SOFTWARE\\Mozilla\\XULRunner\\Applications\\";
  4243.             var branch = settingsThingy.getBranch(appPrefix + targetApp.id);
  4244.             var path = branch.getProperty("ExtensionsLocation");
  4245.             var destination = Cc["@mozilla.org/file/local;1"].
  4246.                               createInstance(Ci.nsILocalFile);
  4247.             destination.initWithPath(path);
  4248.             xpiFile.copyTo(file, xpiFile.leafName);
  4249.           }
  4250.           catch (e) {
  4251.           }
  4252.          */
  4253.         }
  4254.       }
  4255.     }
  4256.  
  4257.     /**
  4258.      * Extracts and then starts the install for extensions / themes contained
  4259.      * within a xpi.
  4260.      */
  4261.     function installMultiXPI(xpiFile, installData) {
  4262.       var fileURL = getURIFromFile(xpiFile).QueryInterface(Ci.nsIURL);
  4263.       if (fileURL.fileExtension.toLowerCase() != "xpi") {
  4264.         LOG("Invalid File Extension: Item: \"" + fileURL.fileName + "\" has an " +
  4265.             "invalid file extension. Only xpi file extensions are allowed for " +
  4266.             "multiple item packages.");
  4267.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4268.         showMessage("invalidFileExtTitle", [],
  4269.                     "invalidFileExtMessage", [installData.name,
  4270.                     fileURL.fileExtension,
  4271.                     bundle.GetStringFromName("type-" + installData.type)]);
  4272.         return;
  4273.       }
  4274.  
  4275.       try {
  4276.         var zipReader = getZipReaderForFile(xpiFile);
  4277.       }
  4278.       catch (e) {
  4279.         LOG("installMultiXPI: failed to open xpi file: " + xpiFile.path);
  4280.         throw e;
  4281.       }
  4282.  
  4283.       var searchForEntries = ["*.xpi", "*.jar"];
  4284.       var files = [];
  4285.       for (var i = 0; i < searchForEntries.length; ++i) {
  4286.         var entries = zipReader.findEntries(searchForEntries[i]);
  4287.         while (entries.hasMore()) {
  4288.           var entryName = entries.getNext();
  4289.           var target = getFile(KEY_TEMPDIR, [entryName]);
  4290.           try {
  4291.             target.createUnique(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4292.           }
  4293.           catch (e) {
  4294.             LOG("installMultiXPI: failed to create target file for extraction " +
  4295.                 " file = " + target.path + ", exception = " + e + "\n");
  4296.           }
  4297.           zipReader.extract(entryName, target);
  4298.           files.push(target);
  4299.         }
  4300.       }
  4301.       zipReader.close();
  4302.  
  4303.       if (files.length == 0) {
  4304.         LOG("Multiple Item Package: Item: \"" + fileURL.fileName + "\" does " +
  4305.             "not contain a valid package to install.");
  4306.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4307.         showMessage("missingPackageFilesTitle",
  4308.                     [bundle.GetStringFromName("type-" + installData.type)],
  4309.                     "missingPackageFilesMessage", [installData.name,
  4310.                     bundle.GetStringFromName("type-" + installData.type)]);
  4311.         return;
  4312.       }
  4313.  
  4314.       for (i = 0; i < files.length; ++i) {
  4315.         em.installItemFromFileInternal(files[i], aInstallLocationKey, null);
  4316.         files[i].remove(false);
  4317.       }
  4318.     }
  4319.  
  4320.     /**
  4321.      * An observer for the Extension Update System.
  4322.      * @constructor
  4323.      */
  4324.     function IncompatibleObserver() {}
  4325.     IncompatibleObserver.prototype = {
  4326.       _xpi: null,
  4327.       _installManifest: null,
  4328.  
  4329.       /**
  4330.        * Ask the Extension Update System if there are any version updates for
  4331.        * this item that will allow it to be compatible with this version of
  4332.        * the Application.
  4333.        * @param   item
  4334.        *          An nsIUpdateItem representing the item being installed.
  4335.        * @param   installManifest
  4336.        *          The Install Manifest datasource for the item.
  4337.        * @param   xpiFile
  4338.        *          The staged source XPI file that contains the item. Cleaned
  4339.        *          up by this process.
  4340.        * @param   installRDF
  4341.        *          The install.rdf file that was extracted from the xpi.
  4342.        */
  4343.       checkForUpdates: function(item, installManifest, xpiFile) {
  4344.         this._xpi             = xpiFile;
  4345.         this._installManifest = installManifest;
  4346.  
  4347.         for (var i = 0; i < em._installListeners.length; ++i)
  4348.           em._installListeners[i].onCompatibilityCheckStarted(item);
  4349.         em._compatibilityCheckCount++;
  4350.         em.update([item], 1, Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY, this);
  4351.       },
  4352.  
  4353.       /**
  4354.        * See nsIExtensionManager.idl
  4355.        */
  4356.       onUpdateStarted: function() {
  4357.         LOG("Phone Home Listener: Update Started");
  4358.       },
  4359.  
  4360.       /**
  4361.        * See nsIExtensionManager.idl
  4362.        */
  4363.       onUpdateEnded: function() {
  4364.         LOG("Phone Home Listener: Update Ended");
  4365.       },
  4366.  
  4367.       /**
  4368.        * See nsIExtensionManager.idl
  4369.        */
  4370.       onAddonUpdateStarted: function(addon) {
  4371.         if (!addon)
  4372.           throw Cr.NS_ERROR_INVALID_ARG;
  4373.  
  4374.         LOG("Phone Home Listener: Update For " + addon.id + " started");
  4375.         em.datasource.addIncompatibleUpdateItem(addon.name, this._xpi.path,
  4376.                                                 addon.type, addon.version);
  4377.       },
  4378.  
  4379.       /**
  4380.        * See nsIExtensionManager.idl
  4381.        */
  4382.       onAddonUpdateEnded: function(addon, status) {
  4383.         if (!addon)
  4384.           throw Cr.NS_ERROR_INVALID_ARG;
  4385.  
  4386.         LOG("Phone Home Listener: Update For " + addon.id + " ended, status = " + status);
  4387.         em.datasource.removeDownload(this._xpi.path);
  4388.         LOG("Version Check Phone Home Completed");
  4389.  
  4390.         for (var i = 0; i < em._installListeners.length; ++i)
  4391.           em._installListeners[i].onCompatibilityCheckEnded(addon, status);
  4392.  
  4393.         // Only compatibility updates (e.g. STATUS_VERSIONINFO) are currently
  4394.         // supported
  4395.         if (status == Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO) {
  4396.           em.datasource.setTargetApplicationInfo(addon.id,
  4397.                                                  addon.targetAppID,
  4398.                                                  addon.minAppVersion,
  4399.                                                  addon.maxAppVersion,
  4400.                                                  this._installManifest);
  4401.  
  4402.           // Try and install again, but use the updated compatibility DB.
  4403.           // This will send out an apropriate onInstallEnded notification for us.
  4404.           em.installItemFromFileInternal(this._xpi, aInstallLocationKey,
  4405.                                          this._installManifest);
  4406.  
  4407.           // Add the updated compatibility info to the datasource if done
  4408.           if (StartupCache.entries[aInstallLocationKey][addon.id].op == OP_NONE) {
  4409.             em.datasource.setTargetApplicationInfo(addon.id,
  4410.                                                    addon.targetAppID,
  4411.                                                    addon.minAppVersion,
  4412.                                                    addon.maxAppVersion,
  4413.                                                    null);
  4414.           }
  4415.           else { // needs a restart
  4416.             // Add updatedMinVersion and updatedMaxVersion so it can be used
  4417.             // to update the datasource during the installation or upgrade.
  4418.             em.datasource.setUpdatedTargetAppInfo(addon.id,
  4419.                                                   addon.targetAppID,
  4420.                                                   addon.minAppVersion,
  4421.                                                   addon.maxAppVersion,
  4422.                                                   null);
  4423.           }
  4424.         }
  4425.         else {
  4426.           em.datasource.removeDownload(this._xpi.path);
  4427.           showIncompatibleError(installData);
  4428.           LOG("Add-on " + addon.id + " is incompatible with " +
  4429.               BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4430.               gApp.platformVersion + ". Remote compatibility check did not " +
  4431.               "resolve this.");
  4432.           
  4433.           for (var i = 0; i < em._installListeners.length; ++i)
  4434.             em._installListeners[i].onInstallEnded(addon, INSTALLERROR_INCOMPATIBLE_VERSION);
  4435.  
  4436.           // We are responsible for cleaning up this file!
  4437.           InstallLocations.get(aInstallLocationKey).removeFile(this._xpi);
  4438.         }
  4439.  
  4440.         em._compatibilityCheckCount--;
  4441.         // If there are no more compatibility checks running and no downloads in
  4442.         // progress then the install operations are complete.
  4443.         if (em._compatibilityCheckCount == 0 && em._transactions.length == 0) {
  4444.           for (var i = 0; i < em._installListeners.length; ++i)
  4445.             em._installListeners[i].onInstallsCompleted();
  4446.         }
  4447.       },
  4448.  
  4449.       QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonUpdateCheckListener])
  4450.     }
  4451.  
  4452.     var shouldPhoneHomeIfNecessary = false;
  4453.     if (!aInstallManifest) {
  4454.       // If we were not called with an Install Manifest, we were called from
  4455.       // some other path than the Phone Home system, so we do want to phone
  4456.       // home if the version is incompatible. As this is the first point in the
  4457.       // install process we must notify observers here.
  4458.  
  4459.       var addon = makeItem(getURIFromFile(aXPIFile).spec, "",
  4460.                            aInstallLocationKey, "", "", "",
  4461.                            getURIFromFile(aXPIFile).spec,
  4462.                            "", "", "", "", 0, gApp.id);
  4463.       for (var i = 0; i < this._installListeners.length; ++i)
  4464.         this._installListeners[i].onInstallStarted(addon);
  4465.  
  4466.       shouldPhoneHomeIfNecessary = true;
  4467.       var installManifest = null;
  4468.       var installManifestFile = extractRDFFileToTempDir(aXPIFile,
  4469.                                                         FILE_INSTALL_MANIFEST,
  4470.                                                         true);
  4471.       if (installManifestFile.exists()) {
  4472.         installManifest = getInstallManifest(installManifestFile);
  4473.         installManifestFile.remove(false);
  4474.       }
  4475.       if (!installManifest) {
  4476.         LOG("The Install Manifest supplied by this item is not well-formed. " +
  4477.             "Installation will not proceed.");
  4478.         for (var i = 0; i < this._installListeners.length; ++i)
  4479.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_INVALID_MANIFEST);
  4480.         return;
  4481.       }
  4482.     }
  4483.     else
  4484.       installManifest = aInstallManifest;
  4485.  
  4486.     var installData = this._getInstallData(installManifest);
  4487.     // Recreate the add-on item with the full detail from the install manifest
  4488.     addon = makeItem(installData.id, installData.version,
  4489.                      aInstallLocationKey,
  4490.                      installData.currentApp ? installData.currentApp.minVersion : "",
  4491.                      installData.currentApp ? installData.currentApp.maxVersion : "",
  4492.                      installData.name,
  4493.                      getURIFromFile(aXPIFile).spec,
  4494.                      "", /* XPI Update Hash */
  4495.                      "", /* Icon URL */
  4496.                      installData.updateURL || "",
  4497.                      installData.updateKey || "",
  4498.                      installData.type,
  4499.                      installData.currentApp ? installData.currentApp.id : "");
  4500.  
  4501.     switch (installData.error) {
  4502.     case INSTALLERROR_INCOMPATIBLE_VERSION:
  4503.       // Since the caller cleans up |aXPIFile|, and we're not yet sure whether or
  4504.       // not we need it (we may need it if a remote version bump that makes it
  4505.       // compatible is discovered by the call home) - so we must stage it for
  4506.       // later ourselves.
  4507.       if (shouldPhoneHomeIfNecessary && installData.currentApp) {
  4508.         var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4509.         if (!installLocation)
  4510.           return;
  4511.         var stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4512.         (new IncompatibleObserver(this)).checkForUpdates(addon, installManifest,
  4513.                                                          stagedFile);
  4514.         // Return early to prevent deletion of the install manifest file.
  4515.         return;
  4516.       }
  4517.       else {
  4518.         // XXXben Look up XULRunnerSettingsThingy to see if there is a registered
  4519.         //        app that can handle this item, if so just stage and don't show
  4520.         //        this error!
  4521.         showIncompatibleError(installData);
  4522.         LOG("Add-on " + installData.id + " is incompatible with " +
  4523.             BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4524.             gApp.platformVersion + ". Remote compatibility check was not performed.");
  4525.       }
  4526.       break;
  4527.     case INSTALLERROR_SUCCESS:
  4528.       // Installation of multiple extensions / themes contained within a single xpi.
  4529.       if (installData.type == Ci.nsIUpdateItem.TYPE_MULTI_XPI) {
  4530.         installMultiXPI(aXPIFile, installData);
  4531.         break;
  4532.       }
  4533.  
  4534.       // Stage the extension's XPI so it can be extracted at the next restart.
  4535.       var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4536.       if (!installLocation) {
  4537.         // No cleanup of any of the staged XPI files should be required here,
  4538.         // because this should only ever fail on the first recurse through
  4539.         // this function, BEFORE staging takes place... technically speaking
  4540.         // a location could become readonly during the phone home process,
  4541.         // but that's an edge case I don't care about.
  4542.         for (var i = 0; i < this._installListeners.length; ++i)
  4543.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_RESTRICTED);
  4544.         return;
  4545.       }
  4546.  
  4547.       // Stage a copy of the XPI/JAR file for our own evil purposes...
  4548.       stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4549.  
  4550.       var restartRequired = this.installRequiresRestart(installData.id,
  4551.                                                         installData.type);
  4552.       // Determine which configuration function to use based on whether or not
  4553.       // there is data about this item in our datasource already - if there is
  4554.       // we want to upgrade, otherwise we install fresh.
  4555.       var ds = this.datasource;
  4556.       if (installData.id in ds.visibleItems && ds.visibleItems[installData.id]) {
  4557.         // We enter this function if any data corresponding to an existing GUID
  4558.         // is found, regardless of its Install Location. We need to check before
  4559.         // "upgrading" an item that Install Location of the new item is of equal
  4560.         // or higher priority than the old item, to make sure the datasource only
  4561.         // ever tracks metadata for active items.
  4562.         var oldInstallLocation = this.getInstallLocation(installData.id);
  4563.         if (oldInstallLocation.priority >= installLocation.priority) {
  4564.           this._upgradeItem(installManifest, installData.id, installLocation,
  4565.                             installData.type);
  4566.           if (!restartRequired) {
  4567.             this._finalizeUpgrade(installData.id, installLocation);
  4568.             this._finalizeInstall(installData.id, stagedFile);
  4569.           }
  4570.         }
  4571.       }
  4572.       else {
  4573.         this._configureForthcomingItem(installManifest, installData.id,
  4574.                                         installLocation, installData.type);
  4575.         if (!restartRequired) {
  4576.           this._finalizeInstall(installData.id, stagedFile);
  4577.           if (installData.type == Ci.nsIUpdateItem.TYPE_THEME) {
  4578.             var internalName = this.datasource.getItemProperty(installData.id, "internalName");
  4579.             if (gPref.getBoolPref(PREF_EM_DSS_ENABLED)) {
  4580.               gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, internalName);
  4581.             }
  4582.             else {
  4583.               gPref.setBoolPref(PREF_DSS_SWITCHPENDING, true);
  4584.               gPref.setCharPref(PREF_DSS_SKIN_TO_SELECT, internalName);
  4585.             }
  4586.           }
  4587.         }
  4588.       }
  4589.       this._updateManifests(restartRequired);
  4590.       break;
  4591.     case INSTALLERROR_INVALID_GUID:
  4592.       LOG("Invalid GUID: Item has GUID: \"" + installData.id + "\"" +
  4593.           " which is not well-formed.");
  4594.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4595.       showMessage("incompatibleTitle",
  4596.                   [bundle.GetStringFromName("type-" + installData.type)],
  4597.                   "invalidGUIDMessage", [installData.name, installData.id]);
  4598.       break;
  4599.     case INSTALLERROR_INVALID_VERSION:
  4600.       LOG("Invalid Version: Item: \"" + installData.id + "\" has version " +
  4601.           installData.version + " which is not well-formed.");
  4602.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4603.       showMessage("incompatibleTitle",
  4604.                   [bundle.GetStringFromName("type-" + installData.type)],
  4605.                   "invalidVersionMessage", [installData.name, installData.version]);
  4606.       break;
  4607.     case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  4608.       const osABI = gOSTarget + "_" + gXPCOMABI;
  4609.       LOG("Incompatible Platform: Item: \"" + installData.id + "\" is not " +
  4610.           "compatible with '" + osABI + "'.");
  4611.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4612.       showMessage("incompatibleTitle",
  4613.                   [bundle.GetStringFromName("type-" + installData.type)],
  4614.                   "incompatiblePlatformMessage",
  4615.                   [installData.name, BundleManager.appName, osABI]);
  4616.       break;
  4617.     case INSTALLERROR_BLOCKLISTED:
  4618.       LOG("Blocklisted Item: Item: \"" + installData.id + "\" version " +
  4619.           installData.version + " was not installed.");
  4620.       showBlocklistMessage([installData], true);
  4621.       break;
  4622.     case INSTALLERROR_INSECURE_UPDATE:
  4623.       LOG("No secure updates: Item: \"" + installData.id + "\" version " + 
  4624.           installData.version + " was not installed.");
  4625.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4626.       showMessage("incompatibleTitle", 
  4627.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4628.                   "insecureUpdateMessage", [installData.name]);
  4629.       break;
  4630.     default:
  4631.       break;
  4632.     }
  4633.  
  4634.     // Check to see if this item supports other applications and in that case
  4635.     // stage the the XPI file in the location specified by those applications.
  4636.     stageXPIForOtherApps(aXPIFile, installData);
  4637.  
  4638.     // The install of this item is complete, notify observers
  4639.     for (var i = 0; i < this._installListeners.length; ++i)
  4640.       this._installListeners[i].onInstallEnded(addon, installData.error);
  4641.   },
  4642.  
  4643.   /**
  4644.    * Whether or not this type's installation/uninstallation requires
  4645.    * the application to be restarted.
  4646.    * @param   id
  4647.    *          The GUID of the item
  4648.    * @param   type
  4649.    *          The nsIUpdateItem type of the item
  4650.    * @returns true if installation of an item of this type requires a
  4651.    *          restart.
  4652.    */
  4653.   installRequiresRestart: function(id, type) {
  4654.     switch (type) {
  4655.     case Ci.nsIUpdateItem.TYPE_THEME:
  4656.       var internalName = this.datasource.getItemProperty(id, "internalName");
  4657.       var needsRestart = false;
  4658.       if (gPref.prefHasUserValue(PREF_DSS_SKIN_TO_SELECT))
  4659.         needsRestart = internalName == gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  4660.       if (!needsRestart &&
  4661.           gPref.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN))
  4662.         needsRestart = internalName == gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  4663.       return needsRestart;
  4664.     }
  4665.     return ((type & Ci.nsIUpdateItem.TYPE_ADDON) > 0);
  4666.   },
  4667.  
  4668.   /**
  4669.    * Perform initial configuration on an item that has just or will be
  4670.    * installed. This inserts the item into the appropriate container in the
  4671.    * datasource, so that the application UI shows the item even if it will
  4672.    * not actually be installed until the next restart.
  4673.    * @param   installManifest
  4674.    *          The Install Manifest datasource that describes this item.
  4675.    * @param   id
  4676.    *          The GUID of this item.
  4677.    * @param   installLocation
  4678.    *          The Install Location where this item is installed.
  4679.    * @param   type
  4680.    *          The nsIUpdateItem type of this item.
  4681.    */
  4682.   _configureForthcomingItem: function(installManifest, id, installLocation, type) {
  4683.     var ds = this.datasource;
  4684.     ds.updateVisibleList(id, installLocation.name, false);
  4685.  
  4686.     var name = null;
  4687.     var localized = findClosestLocalizedResource(installManifest, gInstallManifestRoot);
  4688.     if (localized)
  4689.       name = installManifest.GetTarget(localized, EM_R("name"), true);
  4690.     else
  4691.       name = EM_L(getManifestProperty(installManifest, "name"));
  4692.  
  4693.     var props = { name            : name,
  4694.                   version         : EM_L(getManifestProperty(installManifest, "version")),
  4695.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4696.                   installLocation : EM_L(installLocation.name),
  4697.                   type            : EM_I(type),
  4698.                   availableUpdateURL    : null,
  4699.                   availableUpdateHash   : null,
  4700.                   availableUpdateVersion: null,
  4701.                   availableUpdateInfo   : null };
  4702.     ds.setItemProperties(id, props);
  4703.     ds.updateProperty(id, "availableUpdateURL");
  4704.  
  4705.     this._setOp(id, OP_NEEDS_INSTALL);
  4706.  
  4707.     // Insert it into the child list NOW rather than later because:
  4708.     // - extensions installed using the command line need to be a member
  4709.     //   of a container during the install phase for the code to be able
  4710.     //   to identify profile vs. global
  4711.     // - extensions installed through the UI should show some kind of
  4712.     //   feedback to indicate their presence is forthcoming (i.e. they
  4713.     //   will be available after a restart).
  4714.     ds.insertItemIntoContainer(id);
  4715.  
  4716.     this._notifyAction(id, EM_ITEM_INSTALLED);
  4717.   },
  4718.  
  4719.   /**
  4720.    * Perform configuration on an item that has just or will be upgraded.
  4721.    * @param   installManifest
  4722.    *          The Install Manifest datasource that describes this item.
  4723.    * @param   itemID
  4724.    *          The GUID of this item.
  4725.    * @param   installLocation
  4726.    *          The Install Location where this item is installed.
  4727.    * @param   type
  4728.    *          The nsIUpdateItem type of this item.
  4729.    */
  4730.   _upgradeItem: function (installManifest, id, installLocation, type) {
  4731.     // Don't change any props that would need to be reset if the install fails.
  4732.     // They will be reset as appropriate by the upgrade/install process.
  4733.     var ds = this.datasource;
  4734.     ds.updateVisibleList(id, installLocation.name, false);
  4735.     var props = { installLocation : EM_L(installLocation.name),
  4736.                   type            : EM_I(type),
  4737.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4738.                   availableUpdateURL      : null,
  4739.                   availableUpdateHash     : null,
  4740.                   availableUpdateVersion  : null,
  4741.                   availableUpdateInfo     : null };
  4742.     ds.setItemProperties(id, props);
  4743.     ds.updateProperty(id, "availableUpdateURL");
  4744.  
  4745.     this._setOp(id, OP_NEEDS_UPGRADE);
  4746.     this._notifyAction(id, EM_ITEM_UPGRADED);
  4747.   },
  4748.  
  4749.   /**
  4750.    * Completes an Extension's installation.
  4751.    * @param   id
  4752.    *          The GUID of the Extension to install.
  4753.    * @param   file
  4754.    *          The XPI/JAR file to install from. If this is null, we try to
  4755.    *          determine the stage file location from the ID.
  4756.    */
  4757.   _finalizeInstall: function(id, file) {
  4758.     var ds = this.datasource;
  4759.     var type = ds.getItemProperty(id, "type");
  4760.     if (id == 0 || id == -1) {
  4761.       ds.removeCorruptItem(id);
  4762.       return;
  4763.     }
  4764.     var installLocation = this.getInstallLocation(id);
  4765.     if (!installLocation) {
  4766.       // If the install location is null, that means we've reached the finalize
  4767.       // state without the item ever having metadata added for it, which implies
  4768.       // bogus data in the Startup Cache. Clear the entries and don't do anything
  4769.       // else.
  4770.       var entries = StartupCache.findEntries(id);
  4771.       for (var i = 0; i < entries.length; ++i) {
  4772.         var location = InstallLocations.get(entries[i].location);
  4773.         StartupCache.clearEntry(location, id);
  4774.         PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4775.       }
  4776.       return;
  4777.     }
  4778.     var itemLocation = installLocation.getItemLocation(id);
  4779.  
  4780.     if (!file && "stageFile" in installLocation)
  4781.       file = installLocation.getStageFile(id);
  4782.  
  4783.     // If |file| is null or does not exist, the installer assumes the item is
  4784.     // a dropped-in directory.
  4785.     var installer = new Installer(this.datasource, id, installLocation, type);
  4786.     installer.installFromFile(file);
  4787.  
  4788.     // If the file was staged, we must clean it up ourselves, otherwise the
  4789.     // EM caller is responsible for doing so (e.g. XPInstall)
  4790.     if (file)
  4791.       installLocation.removeFile(file);
  4792.  
  4793.     // Clear the op flag from the Startup Cache and Pending Operations sets
  4794.     StartupCache.put(installLocation, id, OP_NONE, true);
  4795.     PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4796.   },
  4797.  
  4798.   /**
  4799.    * Removes an item's metadata in preparation for an upgrade-install.
  4800.    * @param   id
  4801.    *          The GUID of the item to uninstall.
  4802.    * @param   installLocation
  4803.    *          The nsIInstallLocation of the item
  4804.    */
  4805.   _finalizeUpgrade: function(id, installLocation) {
  4806.     // Retrieve the item properties *BEFORE* we clean the resource!
  4807.     var ds = this.datasource;
  4808.  
  4809.     var stagedFile = null;
  4810.     if ("getStageFile" in installLocation)
  4811.       stagedFile = installLocation.getStageFile(id);
  4812.  
  4813.     if (stagedFile)
  4814.       var installRDF = extractRDFFileToTempDir(stagedFile, FILE_INSTALL_MANIFEST, true);
  4815.     else
  4816.       installRDF = installLocation.getItemFile(id, FILE_INSTALL_MANIFEST);
  4817.     if (installRDF.exists()) {
  4818.       var installManifest = getInstallManifest(installRDF);
  4819.       if (installManifest) {
  4820.         var type = getAddonTypeFromInstallManifest(installManifest);
  4821.         var userDisabled = ds.getItemProperty(id, "userDisabled") == "true";
  4822.  
  4823.         // Clean the item resource
  4824.         ds.removeItemMetadata(id);
  4825.         // Now set up the properties on the item to mimic an item in its
  4826.         // "initial state" for installation.
  4827.         this._configureForthcomingItem(installManifest, id, installLocation,
  4828.                                        type);
  4829.         if (userDisabled)
  4830.           ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  4831.       }
  4832.       if (stagedFile)
  4833.         installRDF.remove(false);
  4834.     }
  4835.     // Clear the op flag from the Pending Operations set. Do NOT clear op flag in
  4836.     // the startup cache since this may have been reset to OP_NEEDS_INSTALL by
  4837.     // |_configureForthcomingItem|.
  4838.     PendingOperations.clearItem(OP_NEEDS_UPGRADE, id);
  4839.   },
  4840.  
  4841.   /**
  4842.    * Completes an item's uninstallation.
  4843.    * @param   id
  4844.    *          The GUID of the item to uninstall.
  4845.    */
  4846.   _finalizeUninstall: function(id) {
  4847.     var ds = this.datasource;
  4848.  
  4849.     var installLocation = this.getInstallLocation(id);
  4850.     if (!installLocation.itemIsManagedIndependently(id)) {
  4851.       try {
  4852.         // Having a callback that does nothing just causes the directory to be
  4853.         // removed.
  4854.         safeInstallOperation(id, installLocation,
  4855.                              { data: null, callback: function() { } });
  4856.       }
  4857.       catch (e) {
  4858.         ERROR("_finalizeUninstall: failed to remove directory for item: " + id +
  4859.               " at Install Location: " + installLocation.name + ", rolling back uninstall");
  4860.         var manifest = installLocation.getItemFile(id, "FILE_INSTALL_MANIFEST");
  4861.         // If there is no manifest then either the rollback failed, or there was
  4862.         // no manifest in the first place. Either way this item is now invalid
  4863.         // and we shouldn't try to re-install it.
  4864.         if (manifest.exists()) {
  4865.           // Removal of the files failed, reset the uninstalled flag and rewrite
  4866.           // the install manifests so this item's components are registered.
  4867.           // Clear the op flag from the Startup Cache
  4868.           StartupCache.put(installLocation, id, OP_NONE, true);
  4869.           var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  4870.           this._updateManifests(restartRequired);
  4871.           return;
  4872.         }
  4873.       }
  4874.     }
  4875.     else if (installLocation.name == KEY_APP_PROFILE ||
  4876.              installLocation.name == KEY_APP_GLOBAL ||
  4877.              installLocation.name == KEY_APP_SYSTEM_USER) {
  4878.       // Check for a pointer file and remove it if it exists
  4879.       var pointerFile = installLocation.location.clone();
  4880.       pointerFile.append(id);
  4881.       if (pointerFile.exists() && !pointerFile.isDirectory())
  4882.         pointerFile.remove(false);
  4883.     }
  4884.  
  4885.     // Clean the item resource
  4886.     ds.removeItemMetadata(id);
  4887.  
  4888.     // Do this LAST since inferences are made about an item based on
  4889.     // what container it's in.
  4890.     ds.removeItemFromContainer(id);
  4891.  
  4892.     // Clear the op flag from the Startup Cache and the Pending Operations set.
  4893.     StartupCache.clearEntry(installLocation, id);
  4894.     PendingOperations.clearItem(OP_NEEDS_UNINSTALL, id);
  4895.   },
  4896.  
  4897.   /**
  4898.    * Uninstalls an item. If the uninstallation cannot be performed immediately
  4899.    * it is scheduled for the next restart.
  4900.    * @param   id
  4901.    *          The GUID of the item to uninstall.
  4902.    */
  4903.   uninstallItem: function(id) {
  4904.     var ds = this.datasource;
  4905.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  4906.     if (!ds.isDownloadItem(id)) {
  4907.       var opType = ds.getItemProperty(id, "opType");
  4908.       var installLocation = this.getInstallLocation(id);
  4909.       // Removes any staged xpis for this item.
  4910.       if (opType == OP_NEEDS_UPGRADE || opType == OP_NEEDS_INSTALL) {
  4911.         var stageFile = installLocation.getStageFile(id);
  4912.         if (stageFile)
  4913.           installLocation.removeFile(stageFile);
  4914.       }
  4915.       // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  4916.       // and are removed immediately since the uninstall can't be canceled.
  4917.       if (opType == OP_NEEDS_INSTALL) {
  4918.         ds.removeItemMetadata(id);
  4919.         ds.removeItemFromContainer(id);
  4920.         ds.updateVisibleList(id, null, true);
  4921.         StartupCache.clearEntry(installLocation, id);
  4922.         this._updateManifests(false);
  4923.       }
  4924.       else {
  4925.         if (opType == OP_NEEDS_UPGRADE)
  4926.           ds.setItemProperty(id, "newVersion", null);
  4927.         this._setOp(id, OP_NEEDS_UNINSTALL);
  4928.         var type = ds.getItemProperty(id, "type");
  4929.         var restartRequired = this.installRequiresRestart(id, type);
  4930.         if (!restartRequired) {
  4931.           this._finalizeUninstall(id);
  4932.           this._updateManifests(restartRequired);
  4933.         }
  4934.       }
  4935.     }
  4936.     else {
  4937.       // Bad download entry - uri is url, e.g. "http://www.foo.com/test.xpi"
  4938.       // ... just remove it from the list.
  4939.       ds.removeCorruptDLItem(id);
  4940.     }
  4941.  
  4942.     this._notifyAction(id, EM_ITEM_UNINSTALLED);
  4943.   },
  4944.  
  4945.   /* See nsIExtensionManager.idl */
  4946.   cancelInstallItem: function(id) {
  4947.     var ds = this.datasource;
  4948.     var opType = ds.getItemProperty(id, "opType");
  4949.     if (opType != OP_NEEDS_UPGRADE && opType != OP_NEEDS_INSTALL)
  4950.       return;
  4951.  
  4952.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  4953.     var installLocation = this.getInstallLocation(id);
  4954.     // Removes any staged xpis for this item.
  4955.     var stageFile = installLocation.getStageFile(id);
  4956.     if (stageFile)
  4957.       installLocation.removeFile(stageFile);
  4958.     // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  4959.     // and just need to be removed completely from the ds.
  4960.     if (opType == OP_NEEDS_INSTALL) {
  4961.       ds.removeItemMetadata(id);
  4962.       ds.removeItemFromContainer(id);
  4963.       ds.updateVisibleList(id, null, true);
  4964.       StartupCache.clearEntry(installLocation, id);
  4965.       this._updateManifests(false);
  4966.       this._notifyAction(id, EM_ITEM_CANCEL);
  4967.     }
  4968.     else {
  4969.       // Clear upgrade information and reset any request to enable/disable.
  4970.       ds.setItemProperty(id, EM_R("newVersion"), null);
  4971.       var appDisabled = ds.getItemProperty(id, "appDisabled");
  4972.       var userDisabled = ds.getItemProperty(id, "userDisabled");
  4973.       if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  4974.         this._setOp(id, OP_NONE);
  4975.         this._notifyAction(id, EM_ITEM_CANCEL);
  4976.       }
  4977.       else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  4978.         this._setOp(id, OP_NEEDS_DISABLE);
  4979.         this._notifyAction(id, EM_ITEM_DISABLED);
  4980.       }
  4981.       else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  4982.         this._setOp(id, OP_NEEDS_ENABLE);
  4983.         this._notifyAction(id, EM_ITEM_ENABLED);
  4984.       }
  4985.       else {
  4986.         this._setOp(id, OP_NONE);
  4987.         this._notifyAction(id, EM_ITEM_CANCEL);
  4988.       }
  4989.     }
  4990.   },
  4991.  
  4992.   /**
  4993.    * Cancels a pending uninstall of an item
  4994.    * @param   id
  4995.    *          The ID of the item.
  4996.    */
  4997.   cancelUninstallItem: function(id) {
  4998.     var ds = this.datasource;
  4999.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5000.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5001.     if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  5002.       this._setOp(id, OP_NONE);
  5003.       this._notifyAction(id, EM_ITEM_CANCEL);
  5004.     }
  5005.     else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  5006.       this._setOp(id, OP_NEEDS_DISABLE);
  5007.       this._notifyAction(id, EM_ITEM_DISABLED);
  5008.     }
  5009.     else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  5010.       this._setOp(id, OP_NEEDS_ENABLE);
  5011.       this._notifyAction(id, EM_ITEM_ENABLED);
  5012.     }
  5013.     else {
  5014.       this._setOp(id, OP_NONE);
  5015.       this._notifyAction(id, EM_ITEM_CANCEL);
  5016.     }
  5017.   },
  5018.  
  5019.   /**
  5020.    * Sets the pending operation for a visible item.
  5021.    * @param   id
  5022.    *          The GUID of the item
  5023.    * @param   op
  5024.    *          The name of the operation to be performed
  5025.    */
  5026.   _setOp: function(id, op) {
  5027.     var location = this.getInstallLocation(id);
  5028.     StartupCache.put(location, id, op, true);
  5029.     PendingOperations.addItem(op, { locationKey: location.name, id: id });
  5030.     var ds = this.datasource;
  5031.     if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE)
  5032.       ds.updateDownloadState(PREFIX_ITEM_URI + id, "success");
  5033.  
  5034.     ds.updateProperty(id, "opType");
  5035.     ds.updateProperty(id, "updateable");
  5036.     ds.updateProperty(id, "satisfiesDependencies");
  5037.     var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  5038.     this._updateDependentItemsForID(id);
  5039.     this._updateManifests(restartRequired);
  5040.   },
  5041.  
  5042.   /**
  5043.    * Note on appDisabled and userDisabled property arcs.
  5044.    * The appDisabled and userDisabled RDF property arcs are used to store
  5045.    * the pending operation for app disabling and user disabling for an item as
  5046.    * well as the user and app disabled status after the pending operation has
  5047.    * been completed upon restart. When the appDisabled value changes the value
  5048.    * of userDisabled is reset to prevent the state of widgets and status
  5049.    * messages from being in an incorrect state.
  5050.    */
  5051.  
  5052.   /**
  5053.    * Enables an item for the application (e.g. the item satisfies all
  5054.    * requirements like app compatibility for it to be enabled). The appDisabled
  5055.    * property arc will be removed if the item will be app disabled on next
  5056.    * restart to cancel the app disabled operation for the item otherwise the
  5057.    * property value will be set to OP_NEEDS_ENABLE. The item's pending
  5058.    * operations are then evaluated in order to set the operation to perform
  5059.    * and notify the observers if the operation has been changed.
  5060.    * See "Note on appDisabled and userDisabled property arcs" above.
  5061.    * @param   id
  5062.    *          The ID of the item to be enabled by the application.
  5063.    */
  5064.   _appEnableItem: function(id) {
  5065.     var ds = this.datasource;
  5066.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5067.     if (appDisabled == OP_NONE || appDisabled == OP_NEEDS_ENABLE)
  5068.       return;
  5069.  
  5070.     var opType = ds.getItemProperty(id, "opType");
  5071.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5072.     // reset user disabled if it has a pending operation to prevent the ui
  5073.     // state from getting confused as to an item's current state.
  5074.     if (userDisabled == OP_NEEDS_DISABLE)
  5075.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5076.     else if (userDisabled == OP_NEEDS_ENABLE)
  5077.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5078.  
  5079.     if (appDisabled == OP_NEEDS_DISABLE)
  5080.       ds.setItemProperty(id, EM_R("appDisabled"), null);
  5081.     else if (appDisabled == "true")
  5082.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_ENABLE));
  5083.  
  5084.     // Don't set a new operation when there is a pending uninstall operation.
  5085.     if (opType == OP_NEEDS_UNINSTALL) {
  5086.       this._updateDependentItemsForID(id);
  5087.       return;
  5088.     }
  5089.  
  5090.     var operation, action;
  5091.     // if this item is already enabled or user disabled don't set a pending
  5092.     // operation - instead immediately enable it and reset the operation type
  5093.     // if needed.
  5094.     if (appDisabled == OP_NEEDS_DISABLE || appDisabled == OP_NONE ||
  5095.         userDisabled == "true") {
  5096.       if (opType != OP_NONE) {
  5097.         operation = OP_NONE;
  5098.         action = EM_ITEM_CANCEL;
  5099.       }
  5100.     }
  5101.     else {
  5102.       if (opType != OP_NEEDS_ENABLE) {
  5103.         operation = OP_NEEDS_ENABLE;
  5104.         action = EM_ITEM_ENABLED;
  5105.       }
  5106.     }
  5107.  
  5108.     if (action) {
  5109.       this._setOp(id, operation);
  5110.       this._notifyAction(id, action);
  5111.     }
  5112.     else {
  5113.       ds.updateProperty(id, "satisfiesDependencies");
  5114.       this._updateDependentItemsForID(id);
  5115.     }
  5116.   },
  5117.  
  5118.   /**
  5119.    * Disables an item for the application (e.g. the item doesn't satisfy all
  5120.    * requirements like app compatibility for it to be enabled). The appDisabled
  5121.    * property arc will be set to true if the item will be app enabled on next
  5122.    * restart to cancel the app enabled operation for the item otherwise the
  5123.    * property value will be set to OP_NEEDS_DISABLE. The item's pending
  5124.    * operations are then evaluated in order to set the operation to perform
  5125.    * and notify the observers if the operation has been changed.
  5126.    * See "Note on appDisabled and userDisabled property arcs" above.
  5127.    * @param   id
  5128.    *          The ID of the item to be disabled by the application.
  5129.    */
  5130.   _appDisableItem: function(id) {
  5131.     var ds = this.datasource;
  5132.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5133.     if (appDisabled == "true" || appDisabled == OP_NEEDS_DISABLE)
  5134.       return;
  5135.  
  5136.     var opType = ds.getItemProperty(id, "opType");
  5137.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5138.  
  5139.     // reset user disabled if it has a pending operation to prevent the ui
  5140.     // state from getting confused as to an item's current state.
  5141.     if (userDisabled == OP_NEEDS_DISABLE)
  5142.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5143.     else if (userDisabled == OP_NEEDS_ENABLE)
  5144.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5145.  
  5146.     if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE ||
  5147.         ds.getItemProperty(id, "userDisabled") == "true")
  5148.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  5149.     else if (appDisabled == OP_NONE)
  5150.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_DISABLE));
  5151.  
  5152.     // Don't set a new operation when there is a pending uninstall operation.
  5153.     if (opType == OP_NEEDS_UNINSTALL) {
  5154.       this._updateDependentItemsForID(id);
  5155.       return;
  5156.     }
  5157.  
  5158.     var operation, action;
  5159.     // if this item is already disabled don't set a pending operation - instead
  5160.     // immediately disable it and reset the operation type if needed.
  5161.     if (appDisabled == OP_NEEDS_ENABLE || appDisabled == "true" ||
  5162.         userDisabled == OP_NEEDS_ENABLE || userDisabled == "true") {
  5163.       if (opType != OP_NONE) {
  5164.         operation = OP_NONE;
  5165.         action = EM_ITEM_CANCEL;
  5166.       }
  5167.     }
  5168.     else {
  5169.       if (opType != OP_NEEDS_DISABLE) {
  5170.         operation = OP_NEEDS_DISABLE;
  5171.         action = EM_ITEM_DISABLED;
  5172.       }
  5173.     }
  5174.  
  5175.     if (action) {
  5176.       this._setOp(id, operation);
  5177.       this._notifyAction(id, action);
  5178.     }
  5179.     else {
  5180.       ds.updateProperty(id, "satisfiesDependencies");
  5181.       this._updateDependentItemsForID(id);
  5182.     }
  5183.   },
  5184.  
  5185.   /**
  5186.    * Sets an item to be enabled by the user. If the item is already enabled this
  5187.    * clears the needs-enable operation for the next restart.
  5188.    * See "Note on appDisabled and userDisabled property arcs" above.
  5189.    * @param   id
  5190.    *          The ID of the item to be enabled by the user.
  5191.    */
  5192.   enableItem: function(id) {
  5193.     var ds = this.datasource;
  5194.     var opType = ds.getItemProperty(id, "opType");
  5195.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5196.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5197.  
  5198.     var operation, action;
  5199.     // if this item is already enabled don't set a pending operation - instead
  5200.     // immediately enable it and reset the operation type if needed.
  5201.     if (appDisabled == OP_NONE &&
  5202.         userDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NONE) {
  5203.       if (userDisabled == OP_NEEDS_DISABLE)
  5204.         ds.setItemProperty(id, EM_R("userDisabled"), null);
  5205.       if (opType != OP_NONE) {
  5206.         operation = OP_NONE;
  5207.         action = EM_ITEM_CANCEL;
  5208.       }
  5209.     }
  5210.     else {
  5211.       if (userDisabled == "true")
  5212.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_ENABLE));
  5213.       if (opType != OP_NEEDS_ENABLE) {
  5214.         operation = OP_NEEDS_ENABLE;
  5215.         action = EM_ITEM_ENABLED;
  5216.       }
  5217.     }
  5218.  
  5219.     if (action) {
  5220.       this._setOp(id, operation);
  5221.       this._notifyAction(id, action);
  5222.     }
  5223.     else {
  5224.       ds.updateProperty(id, "satisfiesDependencies");
  5225.       this._updateDependentItemsForID(id);
  5226.     }
  5227.   },
  5228.  
  5229.   /**
  5230.    * Sets an item to be disabled by the user. If the item is already disabled
  5231.    * this clears the needs-disable operation for the next restart.
  5232.    * See "Note on appDisabled and userDisabled property arcs" above.
  5233.    * @param   id
  5234.    *          The ID of the item to be disabled by the user.
  5235.    */
  5236.   disableItem: function(id) {
  5237.     var ds = this.datasource;
  5238.     var opType = ds.getItemProperty(id, "opType");
  5239.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5240.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5241.  
  5242.     var operation, action;
  5243.     // if this item is already disabled don't set a pending operation - instead
  5244.     // immediately disable it and reset the operation type if needed.
  5245.     if (userDisabled == OP_NEEDS_ENABLE || userDisabled == "true" ||
  5246.         appDisabled == OP_NEEDS_ENABLE) {
  5247.       if (userDisabled != "true")
  5248.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5249.       if (opType != OP_NONE) {
  5250.         operation = OP_NONE;
  5251.         action = EM_ITEM_CANCEL;
  5252.       }
  5253.     }
  5254.     else {
  5255.       if (userDisabled == OP_NONE)
  5256.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_DISABLE));
  5257.       if (opType != OP_NEEDS_DISABLE) {
  5258.         operation = OP_NEEDS_DISABLE;
  5259.         action = EM_ITEM_DISABLED;
  5260.       }
  5261.     }
  5262.  
  5263.     if (action) {
  5264.       this._setOp(id, operation);
  5265.       this._notifyAction(id, action);
  5266.     }
  5267.     else {
  5268.       ds.updateProperty(id, "satisfiesDependencies");
  5269.       this._updateDependentItemsForID(id);
  5270.     }
  5271.   },
  5272.  
  5273.   /**
  5274.    * Determines whether an item should be disabled by the application.
  5275.    * @param   id
  5276.    *          The ID of the item to check
  5277.    */
  5278.   _isUsableItem: function(id) {
  5279.     var ds = this.datasource;
  5280.     /* If we're not compatibility checking or if the item is compatible
  5281.      * and if it isn't blocklisted and has all dependencies satisfied then
  5282.      * proceed to the security check */
  5283.     if ((!gCheckCompatibility || ds.getItemProperty(id, "compatible") == "true") &&
  5284.         ds.getItemProperty(id, "blocklisted") == "false" &&
  5285.         ds.getItemProperty(id, "satisfiesDependencies") == "true") {
  5286.  
  5287.       // appManaged items aren't updated so no need to check update security.
  5288.       if (ds.getItemProperty(id, "appManaged") == "true")
  5289.         return true;
  5290.  
  5291.       /* If we are not ignoring update security then check that the item has
  5292.        * a secure update mechanism */
  5293.       return (!gCheckUpdateSecurity ||
  5294.               ds.getItemProperty(id, "providesUpdatesSecurely") == "true");
  5295.     }
  5296.     return false;
  5297.   },
  5298.  
  5299.   /**
  5300.    * Sets an item's dependent items disabled state for the app based on whether
  5301.    * its dependencies are met and the item is compatible.
  5302.    * @param   id
  5303.    *          The ID of the item whose dependent items will be checked
  5304.    */
  5305.   _updateDependentItemsForID: function(id) {
  5306.     var ds = this.datasource;
  5307.     var dependentItems = this.getDependentItemListForID(id, true, { });
  5308.     for (var i = 0; i < dependentItems.length; ++i) {
  5309.       var dependentID = dependentItems[i].id;
  5310.       ds.updateProperty(dependentID, "satisfiesDependencies");
  5311.       if (this._isUsableItem(dependentID))
  5312.         this._appEnableItem(dependentID);
  5313.       else
  5314.         this._appDisableItem(dependentID);
  5315.     }
  5316.   },
  5317.  
  5318.   /**
  5319.    * Notify observers of a change to an item that has been requested by the
  5320.    * user.
  5321.    */
  5322.   _notifyAction: function(id, reason) {
  5323.     gOS.notifyObservers(this.datasource.getItemForID(id),
  5324.                         EM_ACTION_REQUESTED_TOPIC, reason);
  5325.   },
  5326.  
  5327.   /**
  5328.    * See nsIExtensionManager.idl
  5329.    */
  5330.   update: function(items, itemCount, updateCheckType, listener) {
  5331.     for (i = 0; i < itemCount; ++i) {
  5332.       var currItem = items[i];
  5333.       if (!currItem)
  5334.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5335.     }
  5336.  
  5337.     if (items.length == 0)
  5338.       items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5339.  
  5340.     var updater = new ExtensionItemUpdater(this);
  5341.     updater.checkForUpdates(items, items.length, updateCheckType, listener);
  5342.   },
  5343.  
  5344.  
  5345.   /**
  5346.    * Checks for changes to the blocklist using the local blocklist file,
  5347.    * application disables / enables items that have been added / removed from
  5348.    * the blocklist, and if there are additions to the blocklist this will
  5349.    * inform the user by displaying a list of the items added.
  5350.    *
  5351.    * XXXrstrong - this method is not terribly useful and was added so we can
  5352.    * trigger this check from the additional timer used by blocklisting.
  5353.    */
  5354.   checkForBlocklistChanges: function() {
  5355.     var ds = this.datasource;
  5356.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5357.     for (var i = 0; i < items.length; ++i) {
  5358.       var id = items[i].id;
  5359.       ds.updateProperty(id, "blocklisted");
  5360.       if (this._isUsableItem(id))
  5361.         this._appEnableItem(id);
  5362.     }
  5363.  
  5364.     items = ds.getBlocklistedItemList(null, null, Ci.nsIUpdateItem.TYPE_ANY,
  5365.                                       false);
  5366.     for (i = 0; i < items.length; ++i)
  5367.       this._appDisableItem(items[i].id);
  5368.  
  5369.     // show the blocklist notification window if there are new blocklist items.
  5370.     if (items.length > 0)
  5371.       showBlocklistMessage(items, false);
  5372.   },
  5373.  
  5374.   /**
  5375.    * @returns An enumeration of all registered Install Locations.
  5376.    */
  5377.   get installLocations () {
  5378.     return InstallLocations.enumeration;
  5379.   },
  5380.  
  5381.   /**
  5382.    * Gets the Install Location where a visible Item is stored.
  5383.    * @param   id
  5384.    *          The GUID of the item to locate an Install Location for.
  5385.    * @returns The Install Location object where the item is stored.
  5386.    */
  5387.   getInstallLocation: function(id) {
  5388.     var key = this.datasource.visibleItems[id];
  5389.     return key ? InstallLocations.get(this.datasource.visibleItems[id]) : null;
  5390.   },
  5391.  
  5392.   /**
  5393.    * Gets a nsIUpdateItem for the item with the specified id.
  5394.    * @param   id
  5395.    *          The GUID of the item to construct a nsIUpdateItem for.
  5396.    * @returns The nsIUpdateItem representing the item.
  5397.    */
  5398.   getItemForID: function(id) {
  5399.     return this.datasource.getItemForID(id);
  5400.   },
  5401.  
  5402.   /**
  5403.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  5404.    * on another item.
  5405.    * @param   id
  5406.    *          The ID of the item that other items depend on.
  5407.    * @param   includeDisabled
  5408.    *          Whether to include disabled items in the set returned.
  5409.    * @param   countRef
  5410.    *          The XPCJS reference to the number of items returned.
  5411.    * @returns An array of installed nsIUpdateItems that depend on the item
  5412.    *          specified by the id parameter.
  5413.    */
  5414.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  5415.     return this.datasource.getDependentItemListForID(id, includeDisabled, countRef);
  5416.   },
  5417.  
  5418.   /**
  5419.    * Retrieves a list of nsIUpdateItems of items matching the specified type.
  5420.    * @param   type
  5421.    *          The type of item to return.
  5422.    * @param   countRef
  5423.    *          The XPCJS reference to the number of items returned.
  5424.    * @returns An array of nsIUpdateItems matching the id/type filter.
  5425.    */
  5426.   getItemList: function(type, countRef) {
  5427.     return this.datasource.getItemList(type, countRef);
  5428.   },
  5429.  
  5430.   /* See nsIExtensionManager.idl */
  5431.   getIncompatibleItemList: function(id, appVersion, platformVersion, type, includeDisabled,
  5432.                                     countRef) {
  5433.     var items = this.datasource.getIncompatibleItemList(id, appVersion ? appVersion : undefined,
  5434.                                                         platformVersion ? platformVersion : undefined,
  5435.                                                         type, includeDisabled);
  5436.     countRef.value = items.length;
  5437.     return items;
  5438.   },
  5439.  
  5440.   /**
  5441.    * Move an Item to the index of another item in its container.
  5442.    * @param   movingID
  5443.    *          The ID of the item to be moved.
  5444.    * @param   destinationID
  5445.    *          The ID of an item to move another item to.
  5446.    */
  5447.   moveToIndexOf: function(movingID, destinationID) {
  5448.     this.datasource.moveToIndexOf(movingID, destinationID);
  5449.   },
  5450.  
  5451.   /**
  5452.    * Sorts addons of the specified type by the specified property starting from
  5453.    * the top of their container. If the addons are already sorted then no action
  5454.    * is performed.
  5455.    * @param   type
  5456.    *          The nsIUpdateItem type of the items to sort.
  5457.    * @param   propertyName
  5458.    *          The RDF property name used for sorting.
  5459.    * @param   isAscending
  5460.    *          true to sort ascending and false to sort descending
  5461.    */
  5462.   sortTypeByProperty: function(type, propertyName, isAscending) {
  5463.     this.datasource.sortTypeByProperty(type, propertyName, isAscending);
  5464.   },
  5465.  
  5466.   /////////////////////////////////////////////////////////////////////////////
  5467.   // Downloads
  5468.   _transactions: [],
  5469.   _downloadCount: 0,
  5470.   _compatibilityCheckCount: 0,
  5471.  
  5472.   /**
  5473.    * Ask the user if they really want to quit the application, since this will
  5474.    * cancel one or more Extension/Theme downloads.
  5475.    * @param   subject
  5476.    *          A nsISupportsPRBool which this function sets to false if the user
  5477.    *          wishes to cancel all active downloads and quit the application,
  5478.    *          false otherwise.
  5479.    */
  5480.   _confirmCancelDownloadsOnQuit: function(subject) {
  5481.     // If user has already dismissed quit request, then do nothing
  5482.     if ((subject instanceof Ci.nsISupportsPRBool) && subject.data)
  5483.       return;
  5484.  
  5485.     if (this._downloadCount > 0) {
  5486.       // The observers will be notified again after this so set the download
  5487.       // count to 0 to prevent this dialog from being displayed again.
  5488.       this._downloadCount = 0;
  5489.       var result;
  5490. //@line 5635 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  5491.       result = this._confirmCancelDownloads(this._downloadCount,
  5492.                                             "quitCancelDownloadsAlertTitle",
  5493.                                             "quitCancelDownloadsAlertMsgMacMultiple",
  5494.                                             "quitCancelDownloadsAlertMsgMac",
  5495.                                             "dontQuitButtonMac");
  5496. //@line 5641 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  5497.       if (subject instanceof Ci.nsISupportsPRBool)
  5498.         subject.data = result;
  5499.     }
  5500.   },
  5501.  
  5502.   /**
  5503.    * Ask the user if they really want to go offline, since this will cancel
  5504.    * one or more Extension/Theme downloads.
  5505.    * @param   subject
  5506.    *          A nsISupportsPRBool which this function sets to false if the user
  5507.    *          wishes to cancel all active downloads and go offline, false
  5508.    *          otherwise.
  5509.    */
  5510.   _confirmCancelDownloadsOnOffline: function(subject) {
  5511.     if (this._downloadCount > 0) {
  5512.       result = this._confirmCancelDownloads(this._downloadCount,
  5513.                                             "offlineCancelDownloadsAlertTitle",
  5514.                                             "offlineCancelDownloadsAlertMsgMultiple",
  5515.                                             "offlineCancelDownloadsAlertMsg",
  5516.                                             "dontGoOfflineButton");
  5517.       if (subject instanceof Ci.nsISupportsPRBool)
  5518.         subject.data = result;
  5519.     }
  5520.   },
  5521.  
  5522.   /**
  5523.    * Ask the user whether or not they wish to cancel the Extension/Theme
  5524.    * downloads which are currently under way.
  5525.    * @param   count
  5526.    *          The number of active downloads.
  5527.    * @param   title
  5528.    *          The key of the title for the message box to be displayed
  5529.    * @param   cancelMessageMultiple
  5530.    *          The key of the message to be displayed in the message box
  5531.    *          when there are > 1 active downloads.
  5532.    * @param   cancelMessageSingle
  5533.    *          The key of the message to be displayed in the message box
  5534.    *          when there is just one active download.
  5535.    * @param   dontCancelButton
  5536.    *          The key of the label to be displayed on the "Don't Cancel
  5537.    *          Downloads" button.
  5538.    */
  5539.   _confirmCancelDownloads: function(count, title, cancelMessageMultiple,
  5540.                                     cancelMessageSingle, dontCancelButton) {
  5541.     var bundle = BundleManager.getBundle(URI_DOWNLOADS_PROPERTIES);
  5542.     var title = bundle.GetStringFromName(title);
  5543.     var message, quitButton;
  5544.     if (count > 1) {
  5545.       message = bundle.formatStringFromName(cancelMessageMultiple, [count], 1);
  5546.       quitButton = bundle.formatStringFromName("cancelDownloadsOKTextMultiple", [count], 1);
  5547.     }
  5548.     else {
  5549.       message = bundle.GetStringFromName(cancelMessageSingle);
  5550.       quitButton = bundle.GetStringFromName("cancelDownloadsOKText");
  5551.     }
  5552.     var dontQuitButton = bundle.GetStringFromName(dontCancelButton);
  5553.  
  5554.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  5555.              getService(Ci.nsIWindowMediator);
  5556.     var win = wm.getMostRecentWindow("Extension:Manager");
  5557.     const nsIPromptService = Ci.nsIPromptService;
  5558.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  5559.              getService(nsIPromptService);
  5560.     var flags = (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_0) +
  5561.                 (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_1);
  5562.     var rv = ps.confirmEx(win, title, message, flags, quitButton, dontQuitButton, null, null, { });
  5563.     return rv == 1;
  5564.   },
  5565.  
  5566.   /* See nsIExtensionManager.idl */
  5567.   addDownloads: function(items, itemCount, manager) {
  5568.     if (itemCount == 0)
  5569.       throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5570.  
  5571.     for (i = 0; i < itemCount; ++i) {
  5572.       var currItem = items[i];
  5573.       if (!currItem)
  5574.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5575.     }
  5576.  
  5577.     var ds = this.datasource;
  5578.     // Add observers only if they aren't already added for an active download
  5579.     if (this._downloadCount == 0) {
  5580.       gOS.addObserver(this, "offline-requested", false);
  5581.       gOS.addObserver(this, "quit-application-requested", false);
  5582.     }
  5583.     this._downloadCount += itemCount;
  5584.  
  5585.     var urls = [];
  5586.     var hashes = [];
  5587.     var txnID = Math.round(Math.random() * 100);
  5588.     var txn = new ItemDownloadTransaction(this, txnID);
  5589.     for (var i = 0; i < itemCount; ++i) {
  5590.       var currItem = items[i];
  5591.  
  5592.       txn.addDownload(currItem);
  5593.       urls.push(currItem.xpiURL);
  5594.       hashes.push(currItem.xpiHash ? currItem.xpiHash : null);
  5595.       // if this is an update remove the update metadata to prevent it from
  5596.       // being updated during an install.
  5597.       if (!manager) {
  5598.         var id = currItem.id
  5599.         ds.setItemProperties(id, {
  5600.           availableUpdateURL: null,
  5601.           availableUpdateHash: null,
  5602.           availableUpdateVersion: null,
  5603.           availableUpdateInfo: null
  5604.         });
  5605.         ds.updateProperty(id, "availableUpdateURL");
  5606.         ds.updateProperty(id, "updateable");
  5607.       }
  5608.       var id = !manager ? PREFIX_ITEM_URI + currItem.id : currItem.xpiURL;
  5609.       ds.updateDownloadState(id, "waiting");
  5610.     }
  5611.     this._transactions.push(txn);
  5612.  
  5613.     if (manager) {
  5614.       // XPIManager initiated -- let it know we're ready
  5615.       manager.observe(txn, "xpinstall-progress", "open");
  5616.     }
  5617.     else {
  5618.       // Initiate an install from chrome
  5619.       var xpimgr = Cc["@mozilla.org/xpinstall/install-manager;1"].
  5620.                    createInstance(Ci.nsIXPInstallManager);
  5621.       xpimgr.initManagerWithHashes(urls, hashes, urls.length, txn);
  5622.     }
  5623.   },
  5624.  
  5625.   /**
  5626.    * Download Operation State has changed from one to another.
  5627.    *
  5628.    * The nsIXPIProgressDialog implementation in the download transaction object
  5629.    * forwards notifications through these methods which we then pass on to any
  5630.    * front end objects implementing nsIExtensionDownloadListener that
  5631.    * are listening. We maintain the master state of download operations HERE,
  5632.    * not in the front end, because if the user closes the extension or theme
  5633.    * managers during the downloads we need to maintain state and not terminate
  5634.    * the download/install process.
  5635.    *
  5636.    * @param   transaction
  5637.    *          The ItemDownloadTransaction object receiving the download
  5638.    *          notifications from XPInstall.
  5639.    * @param   addon
  5640.    *          An object representing nsIUpdateItem for the addon being updated
  5641.    * @param   state
  5642.    *          The state we are entering
  5643.    * @param   value
  5644.    *          ???
  5645.    */
  5646.   onStateChange: function(transaction, addon, state, value) {
  5647.     var ds = this.datasource;
  5648.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5649.     const nsIXPIProgressDialog = Ci.nsIXPIProgressDialog;
  5650.     switch (state) {
  5651.     case nsIXPIProgressDialog.DOWNLOAD_START:
  5652.       ds.updateDownloadState(id, "downloading");
  5653.       for (var i = 0; i < this._installListeners.length; ++i)
  5654.         this._installListeners[i].onDownloadStarted(addon);
  5655.       break;
  5656.     case nsIXPIProgressDialog.DOWNLOAD_DONE:
  5657.       for (var i = 0; i < this._installListeners.length; ++i)
  5658.         this._installListeners[i].onDownloadEnded(addon);
  5659.       break;
  5660.     case nsIXPIProgressDialog.INSTALL_START:
  5661.       ds.updateDownloadState(id, "finishing");
  5662.       ds.updateDownloadProgress(id, null);
  5663.       break;
  5664.     case nsIXPIProgressDialog.INSTALL_DONE:
  5665.       --this._downloadCount;
  5666.       // From nsInstall.h
  5667.       // SUCCESS        = 0
  5668.       // USER_CANCELLED = -210
  5669.       if (value != 0 && value != -210 && id != addon.xpiURL) {
  5670.         ds.updateDownloadState(id, "failure");
  5671.         ds.updateDownloadProgress(id, null);
  5672.       }
  5673.       transaction.removeDownload(addon.xpiURL);
  5674.       // A successful install will be passing notifications via installItemFromFile
  5675.       if (value != 0) {
  5676.         for (var i = 0; i < this._installListeners.length; ++i)
  5677.           this._installListeners[i].onInstallEnded(addon, value);
  5678.       }
  5679.       break;
  5680.     case nsIXPIProgressDialog.DIALOG_CLOSE:
  5681.       for (var i = 0; i < this._transactions.length; ++i) {
  5682.         if (this._transactions[i].id == transaction.id) {
  5683.           this._transactions.splice(i, 1);
  5684.           // Remove the observers when all transactions have completed.
  5685.           if (this._transactions.length == 0) {
  5686.             gOS.removeObserver(this, "offline-requested");
  5687.             gOS.removeObserver(this, "quit-application-requested");
  5688.  
  5689.             // If there are no compatibility checks running then the install
  5690.             // operations are complete.
  5691.             if (this._compatibilityCheckCount == 0) {
  5692.               for (var i = 0; i < this._installListeners.length; ++i)
  5693.                 this._installListeners[i].onInstallsCompleted();
  5694.             }
  5695.           }
  5696.           break;
  5697.         }
  5698.       }
  5699.       // Remove any remaining downloads from this transaction
  5700.       transaction.removeAllDownloads();
  5701.       break;
  5702.     }
  5703.   },
  5704.  
  5705.   onProgress: function(addon, value, maxValue) {
  5706.     for (var i = 0; i < this._installListeners.length; ++i)
  5707.       this._installListeners[i].onDownloadProgress(addon, value, maxValue);
  5708.  
  5709.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5710.     var progress = Math.round((value / maxValue) * 100);
  5711.     this.datasource.updateDownloadProgress(id, progress);
  5712.   },
  5713.  
  5714.   _installListeners: [],
  5715.   addInstallListener: function(listener) {
  5716.     for (var i = 0; i < this._installListeners.length; ++i) {
  5717.       if (this._installListeners[i] == listener)
  5718.         return i;
  5719.     }
  5720.     this._installListeners.push(listener);
  5721.     return this._installListeners.length - 1;
  5722.   },
  5723.  
  5724.   removeInstallListenerAt: function(index) {
  5725.     this._installListeners.splice(index, 1);
  5726.   },
  5727.  
  5728.   /**
  5729.    * The Extensions RDF Datasource
  5730.    */
  5731.   _ds: null,
  5732.   _ptr: null,
  5733.  
  5734.   /**
  5735.    * Loads the Extensions Datasource. This should not be called unless:
  5736.    * - a piece of Extensions UI is being shown, or
  5737.    * - on startup and there has been a change to an Install Location
  5738.    * ... it should NOT be called on every startup!
  5739.    */
  5740.   _ensureDS: function() {
  5741.     if (!this._ds) {
  5742.       this._ds = new ExtensionsDataSource(this);
  5743.       if (this._ds) {
  5744.         this._ds.loadExtensions();
  5745.         this._ptr = getContainer(this._ds, this._ds._itemRoot).DataSource;
  5746.         gRDF.RegisterDataSource(this._ptr, true);
  5747.       }
  5748.     }
  5749.   },
  5750.  
  5751.   /**
  5752.    * See nsIExtensionManager.idl
  5753.    */
  5754.   get datasource() {
  5755.     this._ensureDS();
  5756.     return this._ds.QueryInterface(Ci.nsIRDFDataSource);
  5757.   },
  5758.  
  5759.   // nsIClassInfo
  5760.   flags: Ci.nsIClassInfo.SINGLETON,
  5761.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  5762.   getHelperForLanguage: function(language) null,
  5763.   getInterfaces: function(count) {
  5764.     var interfaces = [Ci.nsIExtensionManager, Ci.nsIObserver];
  5765.     count.value = interfaces.length;
  5766.     return interfaces;
  5767.   },
  5768.  
  5769.   classDescription: "Extension Manager",
  5770.   contractID: "@mozilla.org/extensions/manager;1",
  5771.   classID: Components.ID("{8A115FAA-7DCB-4e8f-979B-5F53472F51CF}"),
  5772.   _xpcom_categories: [{ category: "app-startup", service: true }],
  5773.   _xpcom_factory: EmFactory,
  5774.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIExtensionManager,
  5775.                                          Ci.nsITimerCallback,
  5776.                                          Ci.nsIObserver,
  5777.                                          Ci.nsIClassInfo])
  5778. };
  5779.  
  5780. /**
  5781.  * This object implements nsIXPIProgressDialog and represents a collection of
  5782.  * XPI/JAR download and install operations. There is one
  5783.  * ItemDownloadTransaction per back-end XPInstallManager object. We maintain
  5784.  * a collection of separate transaction objects because it's possible to have
  5785.  * multiple separate XPInstall download/install operations going on
  5786.  * simultaneously, each with its own XPInstallManager instance. For instance
  5787.  * you could start downloading two extensions and then download a theme. Each
  5788.  * of these operations would open the appropriate FE and have to be able to
  5789.  * track each operation independently.
  5790.  *
  5791.  * @constructor
  5792.  * @param   manager
  5793.  *          The extension manager creating this transaction
  5794.  * @param   id
  5795.  *          The integer identifier of this transaction
  5796.  */
  5797. function ItemDownloadTransaction(manager, id) {
  5798.   this._manager = manager;
  5799.   this._downloads = [];
  5800.   this.id = id;
  5801. }
  5802. ItemDownloadTransaction.prototype = {
  5803.   _manager    : null,
  5804.   _downloads  : [],
  5805.   id          : -1,
  5806.  
  5807.   /**
  5808.    * Add a download to this transaction
  5809.    * @param   addon
  5810.    *          An object implementing nsIUpdateItem for the item to be downloaded
  5811.    */
  5812.   addDownload: function(addon) {
  5813.     this._downloads.push({ addon: addon, waiting: true });
  5814.     this._manager.datasource.addDownload(addon);
  5815.   },
  5816.  
  5817.   /**
  5818.    * Removes a download from this transaction
  5819.    * @param   url
  5820.    *          The URL to remove
  5821.    */
  5822.   removeDownload: function(url) {
  5823.     this._manager.datasource.removeDownload(url);
  5824.   },
  5825.  
  5826.   /**
  5827.    * Remove all downloads from this transaction
  5828.    */
  5829.   removeAllDownloads: function() {
  5830.     for (var i = 0; i < this._downloads.length; ++i) {
  5831.       var addon = this._downloads[i].addon;
  5832.       this.removeDownload(addon.xpiURL);
  5833.     }
  5834.   },
  5835.  
  5836.   /**
  5837.    * Determine if this transaction is handling the download of a url.
  5838.    * @param   url
  5839.    *          The URL to look for
  5840.    * @returns true if this transaction is downloading the supplied url.
  5841.    */
  5842.   containsURL: function(url) {
  5843.     for (var i = 0; i < this._downloads.length; ++i) {
  5844.       if (this._downloads[i].addon.xpiURL == url)
  5845.         return true;
  5846.     }
  5847.     return false;
  5848.   },
  5849.  
  5850.   /**
  5851.    * See nsIXPIProgressDialog.idl
  5852.    */
  5853.   onStateChange: function(index, state, value) {
  5854.     this._manager.onStateChange(this, this._downloads[index].addon,
  5855.                                 state, value);
  5856.   },
  5857.  
  5858.   /**
  5859.    * See nsIXPIProgressDialog.idl
  5860.    */
  5861.   onProgress: function(index, value, maxValue) {
  5862.     this._manager.onProgress(this._downloads[index].addon, value, maxValue);
  5863.   },
  5864.  
  5865.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIXPIProgressDialog])
  5866. };
  5867.  
  5868. /**
  5869.  * A listener object that watches the background update check and notifies the
  5870.  * user of any updates found.
  5871.  */
  5872. function BackgroundUpdateCheckListener(datasource) {
  5873.   this._emDS = datasource;
  5874. }
  5875. BackgroundUpdateCheckListener.prototype = {
  5876.   _updateCount: 0,
  5877.   _emDS: null,
  5878.  
  5879.   // nsIObserver implementation
  5880.   observe: function(aSubject, aTopic, aData) {
  5881.     if (aTopic != "alertclickcallback")
  5882.       return;
  5883.  
  5884.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  5885.              getService(Ci.nsIWindowMediator);
  5886.     var win = wm.getMostRecentWindow("Extension:Manager");
  5887.     if (win) {
  5888.       win.focus();
  5889.       win.showView("updates");
  5890.       // Don't show the update notification on next startup
  5891.       gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  5892.     }
  5893.     else {
  5894.       const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  5895.       const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  5896.  
  5897.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  5898.                getService(Ci.nsIWindowWatcher);
  5899.       var param = Cc["@mozilla.org/supports-array;1"].
  5900.                   createInstance(Ci.nsISupportsArray);
  5901.       var arg = Cc["@mozilla.org/supports-string;1"].
  5902.                 createInstance(Ci.nsISupportsString);
  5903.       arg.data = "updates";
  5904.       param.AppendElement(arg);
  5905.       ww.openWindow(null, EMURL, null, EMFEATURES, param);
  5906.     }
  5907.   },
  5908.   
  5909.   // nsIAddonUpdateCheckListener implementation
  5910.   onUpdateStarted: function() {
  5911.   },
  5912.  
  5913.   onUpdateEnded: function() {
  5914.     if (this._updateCount > 0 && Cc["@mozilla.org/alerts-service;1"]) {
  5915.       var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  5916.       var title = extensionStrings.GetStringFromName("updateNotificationTitle");
  5917.       var text;
  5918.       if (this._updateCount > 1)
  5919.         text = extensionStrings.formatStringFromName("multipleUpdateNotificationText",
  5920.                                                      [BundleManager.appName, this._updateCount], 2);
  5921.       else
  5922.         text = extensionStrings.formatStringFromName("updateNotificationText",
  5923.                                                      [BundleManager.appName], 1);
  5924.  
  5925.       try {
  5926.         var notifier = Cc["@mozilla.org/alerts-service;1"].
  5927.                        getService(Ci.nsIAlertsService);
  5928.         notifier.showAlertNotification(URI_GENERIC_ICON_XPINSTALL,
  5929.                                        title, text, true, "", this);
  5930.       }
  5931.       catch (e) {
  5932.         LOG("Failed to retrieve alerts service, probably an unsupported " +
  5933.             "platform - " + e);
  5934.       }
  5935.     }
  5936.   },
  5937.  
  5938.   onAddonUpdateStarted: function(item) {
  5939.   },
  5940.  
  5941.   onAddonUpdateEnded: function(item, status) {
  5942.     if (status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE) {
  5943.       var lastupdate = this._emDS.getItemProperty(item.id, "availableUpdateVersion");
  5944.       if (lastupdate != item.version) {
  5945.         gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, true);
  5946.         this._updateCount++;
  5947.       }
  5948.     }
  5949.   }
  5950. };
  5951.  
  5952.  
  5953. /**
  5954.  * A listener object to the update check process that routes notifications to
  5955.  * the right places and keeps the datasource up to date.
  5956.  */
  5957. function AddonUpdateCheckListener(listener, datasource) {
  5958.   this._listener = listener;
  5959.   this._ds = datasource;
  5960. }
  5961. AddonUpdateCheckListener.prototype = {
  5962.   _listener: null,
  5963.   _ds: null,
  5964.  
  5965.   onUpdateStarted: function() {
  5966.     if (this._listener)
  5967.       this._listener.onUpdateStarted();
  5968.     this._ds.onUpdateStarted();
  5969.   },
  5970.  
  5971.   onUpdateEnded: function() {
  5972.     if (this._listener)
  5973.       this._listener.onUpdateEnded();
  5974.     this._ds.onUpdateEnded();
  5975.   },
  5976.  
  5977.   onAddonUpdateStarted: function(addon) {
  5978.     if (this._listener)
  5979.       this._listener.onAddonUpdateStarted(addon);
  5980.     this._ds.onAddonUpdateStarted(addon);
  5981.   },
  5982.  
  5983.   onAddonUpdateEnded: function(addon, status) {
  5984.     if (this._listener)
  5985.       this._listener.onAddonUpdateEnded(addon, status);
  5986.     this._ds.onAddonUpdateEnded(addon, status);
  5987.   }
  5988. };
  5989.  
  5990. ///////////////////////////////////////////////////////////////////////////////
  5991. //
  5992. // ExtensionItemUpdater
  5993. //
  5994. function ExtensionItemUpdater(aEM)
  5995. {
  5996.   this._emDS = aEM._ds;
  5997.   this._em = aEM;
  5998.  
  5999.   getVersionChecker();
  6000. }
  6001.  
  6002. ExtensionItemUpdater.prototype = {
  6003.   _emDS               : null,
  6004.   _em                 : null,
  6005.   _updateCheckType    : 0,
  6006.   _items              : [],
  6007.   _listener           : null,
  6008.  
  6009.   /* ExtensionItemUpdater
  6010. //@line 6180 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  6011.   */
  6012.   checkForUpdates: function(aItems, aItemCount, aUpdateCheckType,
  6013.                             aListener) {
  6014.     this._listener = new AddonUpdateCheckListener(aListener, this._emDS);
  6015.     if (this._listener)
  6016.       this._listener.onUpdateStarted();
  6017.     this._updateCheckType = aUpdateCheckType;
  6018.     this._items = aItems;
  6019.     this._responseCount = aItemCount;
  6020.  
  6021.     // This is the number of extensions/themes/etc that we found updates for.
  6022.     this._updateCount = 0;
  6023.  
  6024.     for (var i = 0; i < aItemCount; ++i) {
  6025.       var e = this._items[i];
  6026.       if (this._listener)
  6027.         this._listener.onAddonUpdateStarted(e);
  6028.       (new RDFItemUpdater(this)).checkForUpdates(e, aUpdateCheckType);
  6029.     }
  6030.  
  6031.     if (this._listener && aItemCount == 0)
  6032.       this._listener.onUpdateEnded();
  6033.   },
  6034.  
  6035.   /////////////////////////////////////////////////////////////////////////////
  6036.   // ExtensionItemUpdater
  6037.   _applyVersionUpdates: function(aLocalItem, aRemoteItem) {
  6038.     var targetAppInfo = this._emDS.getTargetApplicationInfo(aLocalItem.id, this._emDS);
  6039.     // If targetAppInfo is null this is for a new install. If the local item's
  6040.     // maxVersion does not equal the targetAppInfo maxVersion then this is for
  6041.     // an upgrade. In both of these cases return true if the remotely specified
  6042.     // maxVersion is greater than the local item's maxVersion.
  6043.     if (!targetAppInfo ||
  6044.         gVersionChecker.compare(aLocalItem.maxAppVersion, targetAppInfo.maxVersion) != 0) {
  6045.       if (gVersionChecker.compare(aLocalItem.maxAppVersion, aRemoteItem.maxAppVersion) < 0)
  6046.         return true;
  6047.       else
  6048.         return false;
  6049.     }
  6050.  
  6051.     if (gVersionChecker.compare(targetAppInfo.maxVersion, aRemoteItem.maxAppVersion) < 0) {
  6052.       // Remotely specified maxVersion is newer than the maxVersion
  6053.       // for the installed Extension. Apply that change to the datasources.
  6054.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6055.                                           aRemoteItem.targetAppID,
  6056.                                           aRemoteItem.minAppVersion,
  6057.                                           aRemoteItem.maxAppVersion,
  6058.                                           null);
  6059.  
  6060.       // If we got here through |checkForMismatches|, this extension has
  6061.       // already been disabled, re-enable it.
  6062.       var op = StartupCache.entries[aLocalItem.installLocationKey][aLocalItem.id].op;
  6063.       if (op == OP_NEEDS_DISABLE ||
  6064.           this._emDS.getItemProperty(aLocalItem.id, "appDisabled") == "true")
  6065.         this._em._appEnableItem(aLocalItem.id);
  6066.       return true;
  6067.     }
  6068.     else if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_SYNC_COMPATIBILITY)
  6069.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6070.                                           aRemoteItem.targetAppID,
  6071.                                           aRemoteItem.minAppVersion,
  6072.                                           aRemoteItem.maxAppVersion,
  6073.                                           null);
  6074.     return false;
  6075.   },
  6076.  
  6077.   /**
  6078.    * Checks whether a discovered update is valid for install
  6079.    * @param   aLocalItem
  6080.    *          The already installed nsIUpdateItem that the update is for
  6081.    * @param   aRemoteItem
  6082.    *          The nsIUpdateItem we are trying to update to
  6083.    *
  6084.    * @returns true if the item is compatible and is not blocklisted.
  6085.    *          false if the item is not compatible or is blocklisted.
  6086.    */
  6087.   _isValidUpdate: function _isValidUpdate(aLocalItem, aRemoteItem) {
  6088.     var appExtensionsVersion = (aRemoteItem.targetAppID != TOOLKIT_ID) ?
  6089.                                gApp.version :
  6090.                                gApp.platformVersion;
  6091.  
  6092.     var min = aRemoteItem.minAppVersion;
  6093.     var max = aRemoteItem.maxAppVersion;
  6094.     // Check if the update will only run on a newer version of the application.
  6095.     if (!min || gVersionChecker.compare(appExtensionsVersion, min) < 0)
  6096.       return false;
  6097.  
  6098.     // Check if the update will only run on an older version of the application.
  6099.     if (!max || gVersionChecker.compare(appExtensionsVersion, max) > 0)
  6100.       return false;
  6101.  
  6102.     if (!gBlocklist)
  6103.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  6104.                    getService(Ci.nsIBlocklistService);
  6105.     if (gBlocklist.isAddonBlocklisted(aLocalItem.id, aRemoteItem.version,
  6106.                                       null, null))
  6107.       return false;
  6108.  
  6109.     return true;
  6110.   },
  6111.  
  6112.   checkForDone: function(item, status) {
  6113.     if (this._listener) {
  6114.       try {
  6115.         this._listener.onAddonUpdateEnded(item, status);
  6116.       }
  6117.       catch (e) {
  6118.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onAddonUpdateEnded: " + e);
  6119.       }
  6120.     }
  6121.     if (--this._responseCount == 0 && this._listener) {
  6122.       try {
  6123.         this._listener.onUpdateEnded();
  6124.       }
  6125.       catch (e) {
  6126.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onUpdateEnded: " + e);
  6127.       }
  6128.     }
  6129.   },
  6130. };
  6131.  
  6132. /**
  6133.  * Replaces %...% strings in an addon url (update and updateInfo) with
  6134.  * appropriate values.
  6135.  * @param   aItem
  6136.  *          The nsIUpdateItem representing the item
  6137.  * @param   aURI
  6138.  *          The uri to escape
  6139.  * @param   aDS
  6140.  *          The extensions datasource
  6141.  *
  6142.  * @returns the appropriately escaped uri.
  6143.  */
  6144. function escapeAddonURI(aItem, aURI, aDS)
  6145. {
  6146.   var itemStatus = "userEnabled";
  6147.   if (aDS.getItemProperty(aItem.id, "userDisabled") == "true" ||
  6148.       aDS.getItemProperty(aItem.id, "userDisabled") == OP_NEEDS_ENABLE)
  6149.     itemStatus = "userDisabled";
  6150.   else if (aDS.getItemProperty(aItem.id, "type") == Ci.nsIUpdateItem.TYPE_THEME) {
  6151.     var currentSkin = gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  6152.     if (aDS.getItemProperty(aItem.id, "internalName") != currentSkin)
  6153.       itemStatus = "userDisabled";
  6154.   }
  6155.  
  6156.   if (aDS.getItemProperty(aItem.id, "compatible") == "false")
  6157.     itemStatus += ",incompatible";
  6158.   if (aDS.getItemProperty(aItem.id, "blocklisted") == "true")
  6159.     itemStatus += ",blocklisted";
  6160.   if (aDS.getItemProperty(aItem.id, "satisfiesDependencies") == "false")
  6161.     itemStatus += ",needsDependencies";
  6162.  
  6163.   aURI = aURI.replace(/%ITEM_ID%/g, aItem.id);
  6164.   aURI = aURI.replace(/%ITEM_VERSION%/g, aItem.version);
  6165.   aURI = aURI.replace(/%ITEM_MAXAPPVERSION%/g, aItem.maxAppVersion);
  6166.   aURI = aURI.replace(/%ITEM_STATUS%/g, itemStatus);
  6167.   aURI = aURI.replace(/%APP_ID%/g, gApp.ID);
  6168.   aURI = aURI.replace(/%APP_VERSION%/g, gApp.version);
  6169.   aURI = aURI.replace(/%REQ_VERSION%/g, 1);
  6170.   aURI = aURI.replace(/%APP_OS%/g, gOSTarget);
  6171.   aURI = aURI.replace(/%APP_ABI%/g, gXPCOMABI);
  6172.   aURI = aURI.replace(/%APP_LOCALE%/g, gLocale);
  6173.  
  6174.   // Replace custom parameters (names of custom parameters must have at
  6175.   // least 3 characters to prevent lookups for something like %D0%C8)
  6176.   var catMan = null;
  6177.   aURI = aURI.replace(/%(\w{3,})%/g, function(match, param) {
  6178.     if (!catMan) {
  6179.       catMan = Cc["@mozilla.org/categorymanager;1"].
  6180.                getService(Ci.nsICategoryManager);
  6181.     }
  6182.  
  6183.     try {
  6184.       var contractID = catMan.getCategoryEntry(CATEGORY_UPDATE_PARAMS, param);
  6185.       var paramHandler = Cc[contractID].
  6186.                          getService(Ci.nsIPropertyBag2);
  6187.       return paramHandler.getPropertyAsAString(param);
  6188.     }
  6189.     catch(e) {
  6190.       return match;
  6191.     }
  6192.   });
  6193.  
  6194.   // escape() does not properly encode + symbols in any embedded FVF strings.
  6195.   return aURI.replace(/\+/g, "%2B");
  6196. }
  6197.  
  6198. function RDFItemUpdater(aUpdater) {
  6199.   this._updater = aUpdater;
  6200. }
  6201.  
  6202. RDFItemUpdater.prototype = {
  6203.   _updater            : null,
  6204.   _updateCheckType    : 0,
  6205.   _item               : null,
  6206.  
  6207.   checkForUpdates: function(aItem, aUpdateCheckType) {
  6208.     // A preference setting can disable updating for this item
  6209.     try {
  6210.       if (!gPref.getBoolPref(PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, aItem.id))) {
  6211.         var status = Ci.nsIAddonUpdateCheckListener.STATUS_DISABLED;
  6212.         this._updater.checkForDone(aItem, status);
  6213.         return;
  6214.       }
  6215.     }
  6216.     catch (e) { }
  6217.  
  6218.     // Items managed by the app are not checked for updates.
  6219.     var emDS = this._updater._emDS;
  6220.     if (emDS.getItemProperty(aItem.id, "appManaged") == "true") {
  6221.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_APP_MANAGED;
  6222.       this._updater.checkForDone(aItem, status);
  6223.       return;
  6224.     }
  6225.  
  6226.     // Items that have a pending install, uninstall, or upgrade are not checked
  6227.     // for updates.
  6228.     var opType = emDS.getItemProperty(aItem.id, "opType");
  6229.     if (opType) {
  6230.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_PENDING_OP;
  6231.       this._updater.checkForDone(aItem, status);
  6232.       return;
  6233.     }
  6234.  
  6235.     var installLocation = InstallLocations.get(emDS.getInstallLocationKey(aItem.id));
  6236.     // Don't check items for updates that are managed independently
  6237.     if (installLocation && installLocation.itemIsManagedIndependently(aItem.id)) {
  6238.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_NOT_MANAGED;
  6239.       this._updater.checkForDone(aItem, status);
  6240.       return;
  6241.     }
  6242.  
  6243.     // Don't check items for updates if the location can't be written to except
  6244.     // when performing a version only update.
  6245.     if ((aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) &&
  6246.         (!installLocation || !installLocation.canAccess)) {
  6247.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_READ_ONLY;
  6248.       this._updater.checkForDone(aItem, status);
  6249.       return;
  6250.     }
  6251.  
  6252.     this._updateCheckType = aUpdateCheckType;
  6253.     this._item = aItem;
  6254.  
  6255.     // Look for a custom update URI: 1) supplied by a pref, 2) supplied by the
  6256.     // install manifest, 3) the default configuration
  6257.     try {
  6258.       var dsURI = gPref.getComplexValue(PREF_EM_ITEM_UPDATE_URL.replace(/%UUID%/, aItem.id),
  6259.                                         Ci.nsIPrefLocalizedString).data;
  6260.     }
  6261.     catch (e) { }
  6262.     if (!dsURI)
  6263.       dsURI = aItem.updateRDF;
  6264.     if (!dsURI)
  6265.       dsURI = gPref.getCharPref(PREF_UPDATE_DEFAULT_URL);
  6266.  
  6267.     dsURI = escapeAddonURI(aItem, dsURI, emDS);
  6268.  
  6269.     // Verify that the URI provided is valid
  6270.     try {
  6271.       var uri = newURI(dsURI);
  6272.     }
  6273.     catch (e) {
  6274.       LOG("RDFItemUpdater:checkForUpdates: There was an error loading the \r\n" +
  6275.           " update datasource for: " + dsURI + ", item = " + aItem.id + ", error: " + e);
  6276.       this._updater.checkForDone(aItem,
  6277.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6278.       return;
  6279.     }
  6280.  
  6281.     LOG("RDFItemUpdater:checkForUpdates sending a request to server for: " +
  6282.         uri.spec + ", item = " + aItem.objectSource);
  6283.  
  6284.     var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
  6285.                   createInstance(Ci.nsIXMLHttpRequest);
  6286.     request.open("GET", uri.spec, true);
  6287.     request.channel.notificationCallbacks = new BadCertHandler();
  6288.     request.overrideMimeType("text/xml");
  6289.     request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
  6290.  
  6291.     var self = this;
  6292.     request.onerror     = function(event) { self.onXMLError(event, aItem);    };
  6293.     request.onload      = function(event) { self.onXMLLoad(event, aItem);     };
  6294.     request.send(null);
  6295.   },
  6296.  
  6297.   onXMLLoad: function(aEvent, aItem) {
  6298.     var request = aEvent.target;
  6299.     try {
  6300.       checkCert(request.channel);
  6301.     }
  6302.     catch (e) {
  6303.       // This may be overly restrictive in two cases: corporate installations
  6304.       // with a corporate update server using an in-house CA cert (installed
  6305.       // but not "built-in") and lone developers hosting their updates on a
  6306.       // site with a self-signed cert (permanently accepted, otherwise the
  6307.       // BadCertHandler would prevent getting this far). Update checks will
  6308.       // fail in both these scenarios.
  6309.       // How else can we protect the vast majority of updates served from AMO
  6310.       // from the spoofing attack described in bug 340198 while allowing those
  6311.       // other cases? A "hackme" pref? Domain-control certs are cheap, getting
  6312.       // one should not be a barrier in either case.
  6313.       LOG("RDFItemUpdater::onXMLLoad: " + e);
  6314.       this._updater.checkForDone(aItem,
  6315.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6316.       return;
  6317.     }
  6318.     var responseXML = request.responseXML;
  6319.  
  6320.     // If the item does not have an update RDF and returns an error it is not
  6321.     // treated as a failure since all items without an updateURL are checked
  6322.     // for updates on AMO even if they are not hosted there.
  6323.     if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
  6324.         (request.status != 200 && request.status != 0)) {
  6325.       this._updater.checkForDone(aItem, (aItem.updateRDF ? Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE :
  6326.                                                            Ci.nsIAddonUpdateCheckListener.STATUS_NONE));
  6327.       return;
  6328.     }
  6329.  
  6330.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  6331.                     createInstance(Ci.nsIRDFXMLParser)
  6332.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  6333.              createInstance(Ci.nsIRDFDataSource);
  6334.     rdfParser.parseString(ds, request.channel.URI, request.responseText);
  6335.  
  6336.     this.onDatasourceLoaded(ds, aItem);
  6337.   },
  6338.  
  6339.   onXMLError: function(aEvent, aItem) {
  6340.     try {
  6341.       var request = aEvent.target;
  6342.       // the following may throw (e.g. a local file or timeout)
  6343.       var status = request.status;
  6344.     }
  6345.     catch (e) {
  6346.       request = aEvent.target.channel.QueryInterface(Ci.nsIRequest);
  6347.       status = request.status;
  6348.     }
  6349.     // this can fail when a network connection is not present.
  6350.     try {
  6351.       var statusText = request.statusText;
  6352.     }
  6353.     catch (e) {
  6354.       status = 0;
  6355.     }
  6356.     // When status is 0 we don't have a valid channel.
  6357.     if (status == 0)
  6358.       statusText = "nsIXMLHttpRequest channel unavailable";
  6359.  
  6360.     LOG("RDFItemUpdater:onError: There was an error loading the \r\n" +
  6361.         "the update datasource for item " + aItem.id + ", error: " + statusText);
  6362.     this._updater.checkForDone(aItem,
  6363.                                Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6364.   },
  6365.  
  6366.   onDatasourceLoaded: function(aDatasource, aLocalItem) {
  6367.     /*
  6368. //@line 6578 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  6369.     */
  6370.     if (!aDatasource.GetAllResources().hasMoreElements()) {
  6371.       LOG("RDFItemUpdater:onDatasourceLoaded: Datasource empty.\r\n" +
  6372.           "If you are an Extension developer and were expecting there to be\r\n" +
  6373.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6374.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6375.           "\r\nTry checking that: \r\n" +
  6376.           " 1. Your remote RDF file exists at the location.\r\n" +
  6377.           " 2. Your RDF file is valid XML (starts with <?xml version=\"1.0\"?>\r\n" +
  6378.           "    and loads in Firefox displaying pretty printed like other XML documents\r\n" +
  6379.           " 3. Your server is sending the data in the correct MIME\r\n" +
  6380.           "    type (text/xml)");
  6381.     }      
  6382.  
  6383.     // If we have an update key then the update manifest must be signed
  6384.     if (aLocalItem.updateKey) {
  6385.       var extensionRes = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6386.       LOG(extensionRes.Value);
  6387.       var signature = this._getPropertyFromResource(aDatasource, extensionRes, "signature", null);
  6388.       if (signature) {
  6389.         var serializer = new RDFSerializer();
  6390.         try {
  6391.           var updateString = serializer.serializeResource(aDatasource, extensionRes);
  6392.           var verifier = Cc["@mozilla.org/security/datasignatureverifier;1"].
  6393.                          getService(Ci.nsIDataSignatureVerifier);
  6394.           try {
  6395.             if (!verifier.verifyData(updateString, signature, aLocalItem.updateKey)) {
  6396.               LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6397.                   aLocalItem.id + " failed signature check.");
  6398.               this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6399.               return;
  6400.             }
  6401.           }
  6402.           catch (e) {
  6403.             LOG("RDFItemUpdater:onDatasourceLoaded: Failed to verify signature for " +
  6404.                 aLocalItem.id + ". This indicates a malformed update key or signature.");
  6405.             this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6406.             return;
  6407.           }
  6408.         }
  6409.         catch (e) {
  6410.           LOG("RDFItemUpdater:onDatasourceLoaded: Failed to generate signature " +
  6411.               "string for " + aLocalItem.id + ". Serializer threw " + e);
  6412.           this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6413.           return;
  6414.         }
  6415.       }
  6416.       else {
  6417.         LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6418.             aLocalItem.id + " did not contain a signature.");
  6419.         this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6420.         return;
  6421.       }
  6422.     }
  6423.     /* If there is no updateKey either the update was over SSL, or it is an old
  6424.      * addon that we are allowing a grace update. */
  6425.  
  6426.     // Parse the response RDF
  6427.     var newerItem, sameItem;
  6428.  
  6429.     // Firefox 1.0PR+ update.rdf format
  6430.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6431.       // Look for newer versions of this item, we only do this in "normal"
  6432.       // mode... see comment by ExtensionItemUpdater_checkForUpdates
  6433.       // about how we do this in all cases but Install Phone Home - which
  6434.       // only needs to do a version check.
  6435.       newerItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6436.                                            Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  6437.  
  6438.       if (newerItem) {
  6439.         ++this._updater._updateCount;
  6440.         LOG("RDFItemUpdater:onDatasourceLoaded: Found a newer version of this item:\r\n" +
  6441.             newerItem.objectSource);
  6442.       }
  6443.     }
  6444.  
  6445.     // Now look for updated version compatibility metadata for the currently
  6446.     // installed version...
  6447.     sameItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6448.                                         Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY);
  6449.  
  6450.     if (sameItem) {
  6451.       // Install-time updates are not written to the DS because there is no
  6452.       // entry yet, EM just uses the notifications to ascertain (by hand)
  6453.       // whether or not there is a remote maxVersion tweak that makes the
  6454.       // item being installed compatible.
  6455.       if (!this._updater._applyVersionUpdates(aLocalItem, sameItem))
  6456.         sameItem = null;
  6457.       else
  6458.         LOG("RDFItemUpdater:onDatasourceLoaded: Found info about the installed\r\n" +
  6459.             "version of this item: " + sameItem.objectSource);
  6460.     }
  6461.     var item = null, status = Ci.nsIAddonUpdateCheckListener.STATUS_NONE;
  6462.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  6463.         && newerItem) {
  6464.       item = newerItem;
  6465.       status = Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  6466.     }
  6467.     else if (sameItem) {
  6468.       item = sameItem;
  6469.       status = Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO;
  6470.     }
  6471.     else {
  6472.       item = aLocalItem;
  6473.       status = Ci.nsIAddonUpdateCheckListener.STATUS_NO_UPDATE;
  6474.     }
  6475.     // Only one call of this._updater.checkForDone is needed for RDF
  6476.     // responses, since there is only one response per item.
  6477.     this._updater.checkForDone(item, status);
  6478.   },
  6479.  
  6480.   // Get a compulsory property from a resource. Reports an error if the
  6481.   // property was not present.
  6482.   _getPropertyFromResource: function(aDataSource, aSourceResource, aProperty, aLocalItem) {
  6483.     var rv;
  6484.     try {
  6485.       var property = gRDF.GetResource(EM_NS(aProperty));
  6486.       rv = stringData(aDataSource.GetTarget(aSourceResource, property, true));
  6487.       if (rv === undefined)
  6488.         throw Cr.NS_ERROR_FAILURE;
  6489.     }
  6490.     catch (e) {
  6491.       // XXXben show console message "aProperty" not found on aSourceResource.
  6492.       return null;
  6493.     }
  6494.     return rv;
  6495.   },
  6496.  
  6497.   /**
  6498.    * Parses the Firefox 1.0RC1+ update manifest format looking for new versions
  6499.    * of updated compatibility information about the given add-on.
  6500.    * @param   aDataSource
  6501.    *          The update manifest's datasource
  6502.    * @param   aLocalItem
  6503.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6504.    * @param   aUpdateCheckType
  6505.    *          The type of update check being performed. See the constants in
  6506.    *          nsIExtensionManager
  6507.    * @returns An nsIUpdateItem holding the update's information if a valid
  6508.    *          update is found or null if not.
  6509.    */
  6510.   _parseV20UpdateInfo: function(aDataSource, aLocalItem, aUpdateCheckType) {
  6511.     var extensionRes  = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6512.  
  6513.     var updatesArc = gRDF.GetResource(EM_NS("updates"));
  6514.     var updates = aDataSource.GetTarget(extensionRes, updatesArc, true);
  6515.  
  6516.     try {
  6517.       updates = updates.QueryInterface(Ci.nsIRDFResource);
  6518.     }
  6519.     catch (e) {
  6520.       LOG("RDFItemUpdater:_parseV20UpdateInfo: No updates were found for:\r\n" +
  6521.           aLocalItem.id + "\r\n" +
  6522.           "If you are an Extension developer and were expecting there to be\r\n" +
  6523.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6524.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6525.           "\r\nTry checking that: \r\n" +
  6526.           " 1. Your RDF File is correct - e.g. check that there is a top level\r\n" +
  6527.           "    RDF Resource with a URI urn:mozilla:extension:{GUID}, and that\r\n" +
  6528.           "    the <em:updates> listed all have matching GUIDs.");
  6529.       return null;
  6530.     }
  6531.  
  6532.     // Track the newest update found
  6533.     var updatedItem = null;
  6534.  
  6535.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  6536.              getService(Ci.nsIRDFContainerUtils);
  6537.     if (cu.IsContainer(aDataSource, updates)) {
  6538.       var ctr = getContainer(aDataSource, updates);
  6539.  
  6540.       var versions = ctr.GetElements();
  6541.       while (versions.hasMoreElements()) {
  6542.         // There are two different methodologies for collecting version
  6543.         // information depending on whether or not we've been invoked in
  6544.         // "version updates only" mode or "version+newest" mode.
  6545.         var version = versions.getNext().QueryInterface(Ci.nsIRDFResource);
  6546.         var foundItem = this._parseV20Update(aDataSource, version, aLocalItem,
  6547.                                              updatedItem ? updatedItem.version : aLocalItem.version,
  6548.                                              aUpdateCheckType);
  6549.         if (foundItem) {
  6550.           // When not checking for new versions we can bail out on the first
  6551.           // result.
  6552.           if (aUpdateCheckType)
  6553.             return foundItem;
  6554.           updatedItem = foundItem;
  6555.         }
  6556.       }
  6557.     }
  6558.     return updatedItem;
  6559.   },
  6560.  
  6561.   /**
  6562.    * Parses a single version's update entry looking for the best matching
  6563.    * targetApplication entry.
  6564.    * @param   aDataSource
  6565.    *          The update manifest's datasource
  6566.    * @param   aUpdateResource
  6567.    *          The nsIRDFResource of the update entry.
  6568.    * @param   aLocalItem
  6569.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6570.    * @param   aNewestVersionFound
  6571.    *          When checking for new versions holds the newest version of this
  6572.    *          add-on that we know about. Otherwise holds the current version.
  6573.    * @param   aUpdateCheckType
  6574.    *          The type of update check being performed. See the constants in
  6575.    *          nsIExtensionManager
  6576.    * @returns An nsIUpdateItem holding the update's information if a valid
  6577.    *          update is found or null if not.
  6578.    */
  6579.   _parseV20Update: function(aDataSource, aUpdateResource, aLocalItem, aNewestVersionFound, aUpdateCheckType) {
  6580.     var version = this._getPropertyFromResource(aDataSource, aUpdateResource,
  6581.                                                 "version", aLocalItem);
  6582.     /* If we are looking for new versions then test whether this discovered
  6583.      * version is greater than any previously found update. Otherwise check
  6584.      * if this update is for the same version as we have installed. */
  6585.     var result = gVersionChecker.compare(version, aNewestVersionFound);
  6586.     if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION ? result <= 0 : result != 0)
  6587.       return null;
  6588.  
  6589.     var taArc = gRDF.GetResource(EM_NS("targetApplication"));
  6590.     var targetApps = aDataSource.GetTargets(aUpdateResource, taArc, true);
  6591.     
  6592.     // Track the best update we have found so far
  6593.     var newestUpdateItem = null;
  6594.     while (targetApps.hasMoreElements()) {
  6595.       var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  6596.       var appID = this._getPropertyFromResource(aDataSource, targetApp, "id", aLocalItem);
  6597.       if (appID != gApp.ID && appID != TOOLKIT_ID)
  6598.         continue;
  6599.  
  6600.       var updateLink = this._getPropertyFromResource(aDataSource, targetApp, "updateLink", aLocalItem);
  6601.       var updateHash = this._getPropertyFromResource(aDataSource, targetApp, "updateHash", aLocalItem);
  6602.       if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6603.         // New version information is useless without a link to get it from
  6604.         if (!updateLink)
  6605.           continue;
  6606.  
  6607.         /* If the update link is non-ssl and we do not have a hash or the hash
  6608.          * is of an insecure nature then we must ignore this update. Bypass
  6609.          * this if not checking update security. Currently we only consider
  6610.          * the sha hashing algorithms as secure. */
  6611.         if (gCheckUpdateSecurity && updateLink.substring(0, 6) != "https:" && 
  6612.             (!updateHash || updateHash.substring(0, 3) != "sha")) {
  6613.           LOG("RDFItemUpdater:_parseV20Update: Update for " + aLocalItem.id +
  6614.               " at " + updateLink + " ignored because it is insecure. updateLink " +
  6615.               " must be a https url or an updateHash must be specified.");
  6616.           continue;
  6617.         }
  6618.       }
  6619.  
  6620.       var updatedItem = makeItem(aLocalItem.id,
  6621.                                  version,
  6622.                                  aLocalItem.installLocationKey,
  6623.                                  this._getPropertyFromResource(aDataSource, targetApp, "minVersion", aLocalItem),
  6624.                                  this._getPropertyFromResource(aDataSource, targetApp, "maxVersion", aLocalItem),
  6625.                                  aLocalItem.name,
  6626.                                  updateLink,
  6627.                                  updateHash,
  6628.                                  "", /* Icon URL */
  6629.                                  "", /* RDF Update URL */
  6630.                                  "", /* Update Key */
  6631.                                  aLocalItem.type,
  6632.                                  appID);
  6633.  
  6634.       if (this._updater._isValidUpdate(aLocalItem, updatedItem)) {
  6635.         if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6636.           var infourl = this._getPropertyFromResource(aDataSource, targetApp,
  6637.                                                       "updateInfoURL");
  6638.           if (infourl)
  6639.             infourl = EM_L(infourl);
  6640.           this._updater._emDS.setItemProperty(aLocalItem.id,
  6641.                                               EM_R("availableUpdateInfo"),
  6642.                                               infourl);
  6643.         }
  6644.         if (appID == gApp.ID) {
  6645.           // App takes precedence over toolkit.  If we found the app, bail out.
  6646.           return updatedItem;
  6647.         }
  6648.         newestUpdateItem = updatedItem;
  6649.       }
  6650.     }
  6651.     return newestUpdateItem;
  6652.   }
  6653. };
  6654.  
  6655. /**
  6656.  * A serialisation method for RDF data that produces an identical string
  6657.  * provided that the RDF assertions match.
  6658.  * The serialisation is not complete, only assertions stemming from a given
  6659.  * resource are included, multiple references to the same resource are not
  6660.  * permitted, and the RDF prolog and epilog are not included.
  6661.  * RDF Blob and Date literals are not supported.
  6662.  */
  6663. function RDFSerializer()
  6664. {
  6665.   this.cUtils = Cc["@mozilla.org/rdf/container-utils;1"].
  6666.                 getService(Ci.nsIRDFContainerUtils);
  6667.   this.resources = [];
  6668. }
  6669.  
  6670. RDFSerializer.prototype = {
  6671.   INDENT: "  ",      // The indent used for pretty-printing
  6672.   resources: null,   // Array of the resources that have been found
  6673.   
  6674.   /**
  6675.    * Escapes characters from a string that should not appear in XML.
  6676.    * @param string     The string to be escaped
  6677.    * @returns a string with all characters invalid in XML character data
  6678.    *          converted to entity references.
  6679.    */
  6680.   escapeEntities: function(string)
  6681.   {
  6682.     string = string.replace(/&/g, "&");
  6683.     string = string.replace(/</g, "<");
  6684.     string = string.replace(/>/g, ">");
  6685.     string = string.replace(/"/g, """);
  6686.     return string;
  6687.   },
  6688.   
  6689.   /**
  6690.    * Serializes all the elements of an RDF container.
  6691.    * @param ds         The datasource holding the data
  6692.    * @param container  The RDF container to output the child elements of
  6693.    * @param indent     The current level of indent for pretty-printing
  6694.    * @returns a string containing the serialized elements.
  6695.    */
  6696.   serializeContainerItems: function(ds, container, indent)
  6697.   {
  6698.     var result = "";
  6699.     var items = container.GetElements();
  6700.     while (items.hasMoreElements()) {
  6701.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  6702.       result += indent + "<RDF:li>\n"
  6703.       result += this.serializeResource(ds, item, indent + this.INDENT);
  6704.       result += indent + "</RDF:li>\n"
  6705.     }
  6706.     return result;
  6707.   },
  6708.   
  6709.   /**
  6710.    * Serializes all em:* (see EM_NS) properties of an RDF resource except for
  6711.    * the em:signature property. As this serialization is to be compared against
  6712.    * the manifest signature it cannot contain the em:signature property itself.
  6713.    * @param ds         The datasource holding the data
  6714.    * @param resource   The RDF resource to output the properties of
  6715.    * @param indent     The current level of indent for pretty-printing
  6716.    * @returns a string containing the serialized properties.
  6717.    */
  6718.   serializeResourceProperties: function(ds, resource, indent)
  6719.   {
  6720.     var result = "";
  6721.     var items = [];
  6722.     var arcs = ds.ArcLabelsOut(resource);
  6723.     while (arcs.hasMoreElements()) {
  6724.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  6725.       if (arc.ValueUTF8.substring(0, PREFIX_NS_EM.length) != PREFIX_NS_EM)
  6726.         continue;
  6727.       var prop = arc.ValueUTF8.substring(PREFIX_NS_EM.length);
  6728.       if (prop == "signature")
  6729.         continue;
  6730.   
  6731.       var targets = ds.GetTargets(resource, arc, true);
  6732.       while (targets.hasMoreElements()) {
  6733.         var target = targets.getNext();
  6734.         if (target instanceof Ci.nsIRDFResource) {
  6735.           var item = indent + "<em:" + prop + ">\n";
  6736.           item += this.serializeResource(ds, target, indent + this.INDENT);
  6737.           item += indent + "</em:" + prop + ">\n";
  6738.           items.push(item);
  6739.         }
  6740.         else if (target instanceof Ci.nsIRDFLiteral) {
  6741.           items.push(indent + "<em:" + prop + ">" + this.escapeEntities(target.Value) + "</em:" + prop + ">\n");
  6742.         }
  6743.         else if (target instanceof Ci.nsIRDFInt) {
  6744.           items.push(indent + "<em:" + prop + " NC:parseType=\"Integer\">" + target.Value + "</em:" + prop + ">\n");
  6745.         }
  6746.         else {
  6747.           throw new Error("Cannot serialize unknown literal type");
  6748.         }
  6749.       }
  6750.     }
  6751.     items.sort();
  6752.     result += items.join("");
  6753.     return result;
  6754.   },
  6755.   
  6756.   /**
  6757.    * Recursively serializes an RDF resource and all resources it links to.
  6758.    * This will only output EM_NS properties and will ignore any em:signature
  6759.    * property.
  6760.    * @param ds         The datasource holding the data
  6761.    * @param resource   The RDF resource to serialize
  6762.    * @param indent     The current level of indent for pretty-printing.
  6763.    *                   Leave undefined for no indent
  6764.    * @returns a string containing the serialized resource.
  6765.    * @throws if the RDF data contains multiple references to the same resource.
  6766.    */
  6767.   serializeResource: function(ds, resource, indent)
  6768.   {
  6769.     if (this.resources.indexOf(resource) != -1 ) {
  6770.       // We cannot output multiple references to the same resource.
  6771.       throw new Error("Cannot serialize multiple references to "+resource.Value);
  6772.     }
  6773.     if (indent === undefined)
  6774.       indent = "";
  6775.     
  6776.     this.resources.push(resource);
  6777.     var container = null;
  6778.     var type = "Description";
  6779.     if (this.cUtils.IsSeq(ds, resource)) {
  6780.       type = "Seq";
  6781.       container = this.cUtils.MakeSeq(ds, resource);
  6782.     }
  6783.     else if (this.cUtils.IsAlt(ds, resource)) {
  6784.       type = "Alt";
  6785.       container = this.cUtils.MakeAlt(ds, resource);
  6786.     }
  6787.     else if (this.cUtils.IsBag(ds, resource)) {
  6788.       type = "Bag";
  6789.       container = this.cUtils.MakeBag(ds, resource);
  6790.     }
  6791.   
  6792.     var result = indent + "<RDF:" + type;
  6793.     if (!gRDF.IsAnonymousResource(resource))
  6794.       result += " about=\"" + this.escapeEntities(resource.ValueUTF8) + "\"";
  6795.     result += ">\n";
  6796.   
  6797.     if (container)
  6798.       result += this.serializeContainerItems(ds, container, indent + this.INDENT);
  6799.       
  6800.     result += this.serializeResourceProperties(ds, resource, indent + this.INDENT);
  6801.   
  6802.     result += indent + "</RDF:" + type + ">\n";
  6803.     return result;
  6804.   }
  6805. }
  6806.  
  6807. /**
  6808.  * A Datasource that holds Extensions.
  6809.  * - Implements nsIRDFDataSource to drive UI
  6810.  * - Uses a RDF/XML datasource for storage (this is undesirable)
  6811.  *
  6812.  * @constructor
  6813.  */
  6814. function ExtensionsDataSource(em) {
  6815.   this._em = em;
  6816.  
  6817.   this._itemRoot = gRDF.GetResource(RDFURI_ITEM_ROOT);
  6818.   this._defaultTheme = gRDF.GetResource(RDFURI_DEFAULT_THEME);
  6819. }
  6820. ExtensionsDataSource.prototype = {
  6821.   _inner    : null,
  6822.   _em       : null,
  6823.   _itemRoot     : null,
  6824.   _defaultTheme : null,
  6825.  
  6826.   /**
  6827.    * Determines if an item's dependencies are satisfied. An item's dependencies
  6828.    * are satisifed when all items specified in the item's em:requires arc are
  6829.    * installed, enabled, and the version is compatible based on the em:requires
  6830.    * minVersion and maxVersion.
  6831.    * @param   id
  6832.    *          The ID of the item
  6833.    * @returns true if the item's dependencies are satisfied.
  6834.    *          false if the item's dependencies are not satisfied.
  6835.    */
  6836.   satisfiesDependencies: function(id) {
  6837.     var ds = this._inner;
  6838.     var itemResource = getResourceForID(id);
  6839.     var targets = ds.GetTargets(itemResource, EM_R("requires"), true);
  6840.     if (!targets.hasMoreElements())
  6841.       return true;
  6842.  
  6843.     getVersionChecker();
  6844.     var idRes = EM_R("id");
  6845.     var minVersionRes = EM_R("minVersion");
  6846.     var maxVersionRes = EM_R("maxVersion");
  6847.     while (targets.hasMoreElements()) {
  6848.       var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  6849.       var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  6850.       var version = null;
  6851.       version = this.getItemProperty(dependencyID, "version");
  6852.       if (version) {
  6853.         var opType = this.getItemProperty(dependencyID, "opType");
  6854.         if (opType ==  OP_NEEDS_DISABLE || opType == OP_NEEDS_UNINSTALL)
  6855.           return false;
  6856.  
  6857.         if (this.getItemProperty(dependencyID, "userDisabled") == "true" ||
  6858.             this.getItemProperty(dependencyID, "appDisabled") == "true" ||
  6859.             this.getItemProperty(dependencyID, "userDisabled") == OP_NEEDS_DISABLE ||
  6860.             this.getItemProperty(dependencyID, "appDisabled") == OP_NEEDS_DISABLE)
  6861.           return false;
  6862.  
  6863.         var minVersion = stringData(ds.GetTarget(target, minVersionRes, true));
  6864.         var maxVersion = stringData(ds.GetTarget(target, maxVersionRes, true));
  6865.         var compatible = (gVersionChecker.compare(version, minVersion) >= 0 &&
  6866.                           gVersionChecker.compare(version, maxVersion) <= 0);
  6867.         if (!compatible)
  6868.           return false;
  6869.       }
  6870.       else {
  6871.         return false;
  6872.       }
  6873.     }
  6874.  
  6875.     return true;
  6876.   },
  6877.  
  6878.   /**
  6879.    * Determine if an item is compatible
  6880.    * @param   datasource
  6881.    *          The datasource to inspect for compatibility - can be the main
  6882.    *          datasource or an Install Manifest.
  6883.    * @param   source
  6884.    *          The RDF Resource of the item to inspect for compatibility.
  6885.    * @param   appVersion
  6886.    *          The version of the application we are checking for compatibility
  6887.    *          against. If this parameter is undefined, the version of the running
  6888.    *          application is used.
  6889.    * @param   platformVersion
  6890.    *          The version of the toolkit to check compatibility against
  6891.    * @returns true if the item is compatible with this version of the
  6892.    *          application, false, otherwise.
  6893.    */
  6894.   isCompatible: function (datasource, source, appVersion, platformVersion) {
  6895.     // The Default Theme is always compatible.
  6896.     if (source.EqualsNode(this._defaultTheme))
  6897.       return true;
  6898.  
  6899.     var appID = gApp.ID;
  6900.     if (appVersion === undefined)
  6901.       appVersion = gApp.version;
  6902.     if (platformVersion === undefined)
  6903.       var platformVersion = gApp.platformVersion;
  6904.  
  6905.     var targets = datasource.GetTargets(source, EM_R("targetApplication"), true);
  6906.     var idRes = EM_R("id");
  6907.     var minVersionRes = EM_R("minVersion");
  6908.     var maxVersionRes = EM_R("maxVersion");
  6909.     var versionChecker = getVersionChecker();
  6910.     var rv = false;
  6911.     while (targets.hasMoreElements()) {
  6912.       var targetApp = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  6913.       var id          = stringData(datasource.GetTarget(targetApp, idRes, true));
  6914.       var minVersion  = stringData(datasource.GetTarget(targetApp, minVersionRes, true));
  6915.       var maxVersion  = stringData(datasource.GetTarget(targetApp, maxVersionRes, true));
  6916.       if (id == appID) {
  6917.         rv = (versionChecker.compare(appVersion, minVersion) >= 0) &&
  6918.              (versionChecker.compare(appVersion, maxVersion) <= 0);
  6919.         return rv; // App takes precedence over toolkit.
  6920.       }
  6921.  
  6922.       if (id == TOOLKIT_ID) {
  6923.         rv =  (versionChecker.compare(platformVersion, minVersion) >= 0) &&
  6924.               (versionChecker.compare(platformVersion, maxVersion) <= 0);
  6925.         // Keep looping, in case the app id is later.
  6926.       }
  6927.     }
  6928.     return rv;
  6929.   },
  6930.  
  6931.   /**
  6932.    * Gets a list of items that are incompatible with a specific application version.
  6933.    * @param   appID
  6934.    *          The ID of the application - XXXben unused?
  6935.    * @param   appVersion
  6936.    *          The Version of the application to check for incompatibility against.
  6937.    * @param   platformVersion
  6938.    *          The version of the toolkit to check compatibility against
  6939.    * @param   desiredType
  6940.    *          The nsIUpdateItem type of items to look for
  6941.    * @param   includeDisabled
  6942.    *          Whether or not disabled items should be included in the set returned
  6943.    * @returns An array of nsIUpdateItems that are incompatible with the application
  6944.    *          ID/Version supplied.
  6945.    */
  6946.   getIncompatibleItemList: function(appID, appVersion, platformVersion,
  6947.                                     desiredType, includeDisabled) {
  6948.     var items = [];
  6949.     var ctr = getContainer(this._inner, this._itemRoot);
  6950.     var elements = ctr.GetElements();
  6951.     while (elements.hasMoreElements()) {
  6952.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  6953.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  6954.       var type = this.getItemProperty(id, "type");
  6955.       // Skip this item if we're not seeking disabled items
  6956.       if (!includeDisabled && this.getItemProperty(id, "isDisabled") == "true")
  6957.         continue;
  6958.  
  6959.       // If the id of this item matches one of the items potentially installed
  6960.       // with and maintained by this application AND it is installed in the
  6961.       // global install location (i.e. the place installed by the app installer)
  6962.       // it is and can be managed by the update file - it's not an item that has
  6963.       // been manually installed by the user into their profile dir, and as such
  6964.       // it is always compatible with the next release of the application since
  6965.       // we will continue to support it.
  6966.       var locationKey = this.getItemProperty(id, "installLocation");
  6967.       var appManaged = this.getItemProperty(id, "appManaged") == "true";
  6968.       if (appManaged && locationKey == KEY_APP_GLOBAL)
  6969.         continue;
  6970.  
  6971.       if (type != -1 && (type & desiredType) &&
  6972.           !this.isCompatible(this, item, appVersion, platformVersion))
  6973.         items.push(this.getItemForID(id));
  6974.     }
  6975.     return items;
  6976.   },
  6977.  
  6978.   /**
  6979.    * Retrieves a list of items that will be blocklisted by the application for
  6980.    * a specific application or toolkit version.
  6981.    * @param   appVersion
  6982.    *          The Version of the application to check the blocklist against.
  6983.    * @param   platformVersion
  6984.    *          The Version of the toolkit to check the blocklist against.
  6985.    * @param   desiredType
  6986.    *          The nsIUpdateItem type of items to look for
  6987.    * @param   includeAppDisabled
  6988.    *          Whether or not items that are or are already set to be disabled
  6989.    *          by the app on next restart should be included in the set returned
  6990.    * @returns An array of nsIUpdateItems that are blocklisted with the application
  6991.    *          or toolkit version supplied.
  6992.    */
  6993.   getBlocklistedItemList: function(appVersion, platformVersion, desiredType,
  6994.                                    includeAppDisabled) {
  6995.     if (!gBlocklist)
  6996.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  6997.                    getService(Ci.nsIBlocklistService);
  6998.     var items = [];
  6999.     var ctr = getContainer(this._inner, this._itemRoot);
  7000.     var elements = ctr.GetElements();
  7001.     while (elements.hasMoreElements()) {
  7002.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7003.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7004.       var type = this.getItemProperty(id, "type");
  7005.  
  7006.       if (!includeAppDisabled &&
  7007.           (this.getItemProperty(id, "appDisabled") == "true" ||
  7008.           this.getItemProperty(id, "appDisabled") == OP_NEEDS_DISABLE))
  7009.         continue;
  7010.  
  7011.       var version = this.getItemProperty(id, "version");
  7012.       if (type != -1 && (type & desiredType) &&
  7013.           gBlocklist.isAddonBlocklisted(id, version, appVersion, platformVersion))
  7014.         items.push(this.getItemForID(id));
  7015.     }
  7016.     return items;
  7017.   },
  7018.  
  7019.   /**
  7020.    * Gets a list of items of a specific type
  7021.    * @param   desiredType
  7022.    *          The nsIUpdateItem type of items to return
  7023.    * @param   countRef
  7024.    *          The XPCJS reference to the size of the returned array
  7025.    * @returns An array of nsIUpdateItems, populated only with an item for |id|
  7026.    *          if |id| is non-null, otherwise all items matching the specified
  7027.    *          type.
  7028.    */
  7029.   getItemList: function(desiredType, countRef) {
  7030.     var items = [];
  7031.     var ctr = getContainer(this, this._itemRoot);
  7032.     var elements = ctr.GetElements();
  7033.     while (elements.hasMoreElements()) {
  7034.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7035.       var eID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7036.       var type = this.getItemProperty(eID, "type");
  7037.       if (type != -1 && type & desiredType)
  7038.         items.push(this.getItemForID(eID));
  7039.     }
  7040.     countRef.value = items.length;
  7041.     return items;
  7042.   },
  7043.  
  7044.   /**
  7045.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  7046.    * on another item.
  7047.    * @param   id
  7048.    *          The ID of the item that other items depend on.
  7049.    * @param   includeDisabled
  7050.    *          Whether to include disabled items in the set returned.
  7051.    * @param   countRef
  7052.    *          The XPCJS reference to the number of items returned.
  7053.    * @returns An array of installed nsIUpdateItems that depend on the item
  7054.    *          specified by the id parameter.
  7055.    */
  7056.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  7057.     var items = [];
  7058.     var ds = this._inner;
  7059.     var ctr = getContainer(this, this._itemRoot);
  7060.     var elements = ctr.GetElements();
  7061.     while (elements.hasMoreElements()) {
  7062.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7063.       var dependentID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7064.       var targets = ds.GetTargets(e, EM_R("requires"), true);
  7065.       var idRes = EM_R("id");
  7066.       while (targets.hasMoreElements()) {
  7067.         var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7068.         var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  7069.         if (dependencyID == id) {
  7070.           if (!includeDisabled && this.getItemProperty(dependentID, "isDisabled") == "true")
  7071.             continue;
  7072.           items.push(this.getItemForID(dependentID));
  7073.           break;
  7074.         }
  7075.       }
  7076.     }
  7077.     countRef.value = items.length;
  7078.     return items;
  7079.   },
  7080.  
  7081.   /**
  7082.    * Constructs an nsIUpdateItem for the given item ID
  7083.    * @param   id
  7084.    *          The GUID of the item to construct a nsIUpdateItem for
  7085.    * @returns The nsIUpdateItem for the id.
  7086.    */
  7087.   getItemForID: function(id) {
  7088.     if (!this.visibleItems[id])
  7089.       return null;
  7090.  
  7091.     var r = getResourceForID(id);
  7092.     if (!r)
  7093.       return null;
  7094.  
  7095.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  7096.     var updateHash = this.getItemProperty(id, "availableUpdateHash");
  7097.     return makeItem(id,
  7098.                     this.getItemProperty(id, "version"),
  7099.                     this.getItemProperty(id, "installLocation"),
  7100.                     targetAppInfo ? targetAppInfo.minVersion : "",
  7101.                     targetAppInfo ? targetAppInfo.maxVersion : "",
  7102.                     this.getItemProperty(id, "name"),
  7103.                     this.getItemProperty(id, "availableUpdateURL"),
  7104.                     updateHash ? updateHash : "",
  7105.                     this.getItemProperty(id, "iconURL"),
  7106.                     this.getItemProperty(id, "updateURL"),
  7107.                     this.getItemProperty(id, "updateKey"),
  7108.                     this.getItemProperty(id, "type"),
  7109.                     targetAppInfo ? targetAppInfo.appID : gApp.ID);
  7110.   },
  7111.  
  7112.   /**
  7113.    * Gets the name of the Install Location where an item is installed.
  7114.    * @param   id
  7115.    *          The GUID of the item to locate an Install Location for
  7116.    * @returns The string name of the Install Location where the item is
  7117.    *          installed.
  7118.    */
  7119.   getInstallLocationKey: function(id) {
  7120.     return this.getItemProperty(id, "installLocation");
  7121.   },
  7122.  
  7123.   /**
  7124.    * Sets an RDF property on an item in a datasource. Does not create
  7125.    * multiple assertions
  7126.    * @param   datasource
  7127.    *          The target datasource where the property should be set
  7128.    * @param   source
  7129.    *          The RDF Resource to set the property on
  7130.    * @param   property
  7131.    *          The RDF Resource of the property to set
  7132.    * @param   newValue
  7133.    *          The RDF Node containing the new property value
  7134.    */
  7135.   _setProperty: function(datasource, source, property, newValue) {
  7136.     var oldValue = datasource.GetTarget(source, property, true);
  7137.     if (oldValue) {
  7138.       if (newValue)
  7139.         datasource.Change(source, property, oldValue, newValue);
  7140.       else
  7141.         datasource.Unassert(source, property, oldValue);
  7142.     }
  7143.     else if (newValue)
  7144.       datasource.Assert(source, property, newValue, true);
  7145.   },
  7146.  
  7147.   /**
  7148.    * Gets the updated target application info if it exists for an item from
  7149.    * the Extensions datasource during an installation or upgrade.
  7150.    * @param   id
  7151.    *          The ID of the item to discover updated target application info for
  7152.    * @returns A JS Object with the following properties:
  7153.    *          "id"            The id of the item
  7154.    *          "minVersion"    The updated minimum version of the target
  7155.    *                          application that this item can run in
  7156.    *          "maxVersion"    The updated maximum version of the target
  7157.    *                          application that this item can run in
  7158.    */
  7159.   getUpdatedTargetAppInfo: function(id) {
  7160.     // The default theme is always compatible so there is never update info.
  7161.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7162.       return null;
  7163.  
  7164.     var appID = gApp.ID;
  7165.     var r = getResourceForID(id);
  7166.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7167.     if (!targetApps.hasMoreElements())
  7168.       targetApps = this._inner.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7169.     var outData = null;
  7170.     while (targetApps.hasMoreElements()) {
  7171.       var targetApp = targetApps.getNext();
  7172.       if (targetApp instanceof Ci.nsIRDFResource) {
  7173.         try {
  7174.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7175.           // Different target application?
  7176.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7177.             continue;
  7178.           var updatedMinVersion = this._inner.GetTarget(targetApp, EM_R("updatedMinVersion"), true);
  7179.           var updatedMaxVersion = this._inner.GetTarget(targetApp, EM_R("updatedMaxVersion"), true);
  7180.           if (updatedMinVersion && updatedMaxVersion)
  7181.             outData = { id          : id,
  7182.                         targetAppID : foundAppID,
  7183.                         minVersion  : stringData(updatedMinVersion),
  7184.                         maxVersion  : stringData(updatedMaxVersion) };
  7185.           if (foundAppID == appID)
  7186.             return outData;
  7187.         }
  7188.         catch (e) {
  7189.           continue;
  7190.         }
  7191.       }
  7192.     }
  7193.     return outData;
  7194.   },
  7195.  
  7196.   /**
  7197.    * Sets the updated target application info for an item in the Extensions
  7198.    * datasource during an installation or upgrade.
  7199.    * @param   id
  7200.    *          The ID of the item to set updated target application info for
  7201.    * @param   targetAppID
  7202.    *          The target application ID used for checking compatibility for this item.
  7203.    * @param   updatedMinVersion
  7204.    *          The updated minimum version of the target application that this
  7205.    *          item can run in
  7206.    * @param   updatedMaxVersion
  7207.    *          The updated maximum version of the target application that this
  7208.    *          item can run in
  7209.    *
  7210.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7211.    *       their install manifest for compatibility with all apps using a
  7212.    *       specific release of the toolkit.
  7213.    */
  7214.   setUpdatedTargetAppInfo: function(id, targetAppID, updatedMinVersion, updatedMaxVersion) {
  7215.     // The default theme is always compatible so it is never updated.
  7216.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7217.       return;
  7218.  
  7219.     // Version/Dependency Info
  7220.     var updatedMinVersionRes = EM_R("updatedMinVersion");
  7221.     var updatedMaxVersionRes = EM_R("updatedMaxVersion");
  7222.  
  7223.     var appID = gApp.ID;
  7224.     var r = getResourceForID(id);
  7225.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7226.     // add updatedMinVersion and updatedMaxVersion for an install else an upgrade
  7227.     if (!targetApps.hasMoreElements()) {
  7228.       var idRes = EM_R("id");
  7229.       var targetRes = getResourceForID(id);
  7230.       var property = EM_R("targetApplication");
  7231.       var anon = gRDF.GetAnonymousResource();
  7232.       this._inner.Assert(anon, idRes, EM_L(appID), true);
  7233.       this._inner.Assert(anon, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7234.       this._inner.Assert(anon, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7235.       this._inner.Assert(targetRes, property, anon, true);
  7236.     }
  7237.     else {
  7238.       while (targetApps.hasMoreElements()) {
  7239.         var targetApp = targetApps.getNext();
  7240.         if (targetApp instanceof Ci.nsIRDFResource) {
  7241.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7242.           // Different target application?
  7243.           if (foundAppID != targetAppID)
  7244.             continue;
  7245.           this._inner.Assert(targetApp, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7246.           this._inner.Assert(targetApp, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7247.           break;
  7248.         }
  7249.       }
  7250.     }
  7251.     this.Flush();
  7252.   },
  7253.  
  7254.   /**
  7255.    * Gets the target application info for an item from a datasource.
  7256.    * @param   id
  7257.    *          The GUID of the item to discover target application info for
  7258.    * @param   datasource
  7259.    *          The datasource to look up target application info in
  7260.    * @returns A JS Object with the following properties:
  7261.    *          "appID"         The target application ID used for checking
  7262.    *                          compatibility for this item.
  7263.    *          "minVersion"    The minimum version of the target application
  7264.    *                          that this item can run in
  7265.    *          "maxVersion"    The maximum version of the target application
  7266.    *                          that this item can run in
  7267.    *          or null, if no target application data exists for the specified
  7268.    *          id in the supplied datasource.
  7269.    */
  7270.   getTargetApplicationInfo: function(id, datasource) {
  7271.     var appID = gApp.ID;
  7272.     // The default theme is always compatible.
  7273.     if (getResourceForID(id).EqualsNode(this._defaultTheme)) {
  7274.       var ver = gApp.version;
  7275.       return { appID: appID, minVersion: ver, maxVersion: ver };
  7276.     }
  7277.  
  7278.     var r = getResourceForID(id);
  7279.     var targetApps = datasource.GetTargets(r, EM_R("targetApplication"), true);
  7280.     if (!targetApps)
  7281.       return null;
  7282.  
  7283.     if (!targetApps.hasMoreElements())
  7284.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7285.     var outData = null;
  7286.     while (targetApps.hasMoreElements()) {
  7287.       var targetApp = targetApps.getNext();
  7288.       if (targetApp instanceof Ci.nsIRDFResource) {
  7289.         try {
  7290.           var foundAppID = stringData(datasource.GetTarget(targetApp, EM_R("id"), true));
  7291.           // Different target application?
  7292.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7293.             continue;
  7294.  
  7295.           outData = { appID: foundAppID,
  7296.                       minVersion: stringData(datasource.GetTarget(targetApp, EM_R("minVersion"), true)),
  7297.                       maxVersion: stringData(datasource.GetTarget(targetApp, EM_R("maxVersion"), true)) };
  7298.           if (foundAppID == appID)
  7299.             return outData;
  7300.         }
  7301.         catch (e) {
  7302.           continue;
  7303.         }
  7304.       }
  7305.     }
  7306.     return outData;
  7307.   },
  7308.  
  7309.   /**
  7310.    * Sets the target application info for an item in a datasource.
  7311.    * @param   id
  7312.    *          The GUID of the item to discover target application info for
  7313.    * @param   targetAppID
  7314.    *          The target application ID used for checking compatibility for this
  7315.    *          item.
  7316.    * @param   minVersion
  7317.    *          The minimum version of the target application that this item can
  7318.    *          run in
  7319.    * @param   maxVersion
  7320.    *          The maximum version of the target application that this item can
  7321.    *          run in
  7322.    * @param   datasource
  7323.    *          The datasource to look up target application info in
  7324.    *
  7325.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7326.    *       their install manifest for compatibility with all apps using a
  7327.    *       specific release of the toolkit.
  7328.    */
  7329.   setTargetApplicationInfo: function(id, targetAppID, minVersion, maxVersion, datasource) {
  7330.     var targetDataSource = datasource;
  7331.     if (!targetDataSource)
  7332.       targetDataSource = this._inner;
  7333.  
  7334.     var appID = gApp.ID;
  7335.     var r = getResourceForID(id);
  7336.     var targetApps = targetDataSource.GetTargets(r, EM_R("targetApplication"), true);
  7337.     if (!targetApps.hasMoreElements())
  7338.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7339.     while (targetApps.hasMoreElements()) {
  7340.       var targetApp = targetApps.getNext();
  7341.       if (targetApp instanceof Ci.nsIRDFResource) {
  7342.         var foundAppID = stringData(targetDataSource.GetTarget(targetApp, EM_R("id"), true));
  7343.         // Different target application?
  7344.         if (foundAppID != targetAppID)
  7345.           continue;
  7346.  
  7347.         this._setProperty(targetDataSource, targetApp, EM_R("minVersion"), EM_L(minVersion));
  7348.         this._setProperty(targetDataSource, targetApp, EM_R("maxVersion"), EM_L(maxVersion));
  7349.  
  7350.         // If we were setting these properties on the main datasource, flush
  7351.         // it now. (Don't flush changes set on Install Manifests - they are
  7352.         // fleeting).
  7353.         if (!datasource)
  7354.           this.Flush();
  7355.  
  7356.         break;
  7357.       }
  7358.     }
  7359.   },
  7360.  
  7361.   /**
  7362.    * Gets a property of an item
  7363.    * @param   id
  7364.    *          The GUID of the item
  7365.    * @param   property
  7366.    *          The name of the property (excluding EM_NS)
  7367.    * @returns The literal value of the property, or undefined if there is no
  7368.    *          value.
  7369.    */
  7370.   getItemProperty: function(id, property) {
  7371.     var item = getResourceForID(id);
  7372.     if (!item) {
  7373.       LOG("getItemProperty failing for lack of an item. This means getResourceForItem \
  7374.            failed to locate a resource for aItemID (item ID = " + id + ", property = " + property + ")");
  7375.     }
  7376.     else
  7377.       return this._getItemProperty(item, property);
  7378.     return undefined;
  7379.   },
  7380.  
  7381.   /**
  7382.    * Gets a property of an item resource
  7383.    * @param   itemResource
  7384.    *          The RDF Resource of the item
  7385.    * @param   property
  7386.    *          The name of the property (excluding EM_NS)
  7387.    * @returns The literal value of the property, or undefined if there is no
  7388.    *          value.
  7389.    */
  7390.   _getItemProperty: function(itemResource, property) {
  7391.     var target = this.GetTarget(itemResource, EM_R(property), true);
  7392.     var value = stringData(target);
  7393.     if (value === undefined)
  7394.       value = intData(target);
  7395.     return value === undefined ? "" : value;
  7396.   },
  7397.  
  7398.   /**
  7399.    * Sets a property on an item.
  7400.    * @param   id
  7401.    *          The GUID of the item
  7402.    * @param   propertyArc
  7403.    *          The RDF Resource of the property arc
  7404.    * @param   propertyValue
  7405.    *          A nsIRDFLiteral value of the property to be set
  7406.    */
  7407.   setItemProperty: function (id, propertyArc, propertyValue) {
  7408.     var item = getResourceForID(id);
  7409.     this._setProperty(this._inner, item, propertyArc, propertyValue);
  7410.     this.Flush();
  7411.   },
  7412.  
  7413.   /**
  7414.    * Sets one or more properties for an item.
  7415.    * @param   id
  7416.    *          The ID of the item
  7417.    * @param   properties
  7418.    *          A JS object which maps properties to values.
  7419.    */
  7420.   setItemProperties: function (id, properties) {
  7421.     var item = getResourceForID(id);
  7422.     for (var key in properties)
  7423.       this._setProperty(this._inner, item, EM_R(key), properties[key]);
  7424.     this.Flush();
  7425.   },
  7426.  
  7427.   /**
  7428.    * Inserts the RDF resource for an item into a container.
  7429.    * @param   id
  7430.    *          The GUID of the item
  7431.    */
  7432.   insertItemIntoContainer: function(id) {
  7433.     // Get the target container and resource
  7434.     var ctr = getContainer(this._inner, this._itemRoot);
  7435.     var itemResource = getResourceForID(id);
  7436.     // Don't bother adding the extension to the list if it's already there.
  7437.     // (i.e. we're upgrading)
  7438.     var oldIndex = ctr.IndexOf(itemResource);
  7439.     if (oldIndex == -1)
  7440.       ctr.AppendElement(itemResource);
  7441.     this.Flush();
  7442.   },
  7443.  
  7444.   /**
  7445.    * Removes the RDF resource for an item from its container.
  7446.    * @param   id
  7447.    *          The GUID of the item
  7448.    */
  7449.   removeItemFromContainer: function(id) {
  7450.     var ctr = getContainer(this._inner, this._itemRoot);
  7451.     var itemResource = getResourceForID(id);
  7452.     ctr.RemoveElement(itemResource, true);
  7453.     this.Flush();
  7454.   },
  7455.  
  7456.   /**
  7457.    * Removes a corrupt item entry from the extension list added due to buggy
  7458.    * code in previous EM versions!
  7459.    * @param   id
  7460.    *          The GUID of the item
  7461.    */
  7462.   removeCorruptItem: function(id) {
  7463.     this.removeItemMetadata(id);
  7464.     this.removeItemFromContainer(id);
  7465.     this.visibleItems[id] = null;
  7466.   },
  7467.  
  7468.   /**
  7469.    * Removes a corrupt download entry from the list
  7470.    * @param   uri
  7471.    *          The RDF URI of the item.
  7472.    * @returns The RDF Resource of the removed entry
  7473.    */
  7474.   removeCorruptDLItem: function(uri) {
  7475.     var itemResource = gRDF.GetResource(uri);
  7476.     var ctr = getContainer(this._inner, this._itemRoot);
  7477.     if (ctr.IndexOf(itemResource) != -1) {
  7478.       ctr.RemoveElement(itemResource, true);
  7479.       this._cleanResource(itemResource);
  7480.       this.Flush();
  7481.     }
  7482.     return itemResource;
  7483.   },
  7484.  
  7485.   /**
  7486.    * Copies localized properties from an install manifest to the datasource
  7487.    *
  7488.    * @param   installManifest
  7489.    *          The Install Manifest datasource we are copying from
  7490.    * @param   source
  7491.    *          The source resource of the localized properties
  7492.    * @param   target
  7493.    *          The target resource to store the localized properties
  7494.    */
  7495.   _addLocalizedMetadata: function(installManifest, sourceRes, targetRes)
  7496.   {
  7497.     var singleProps = ["name", "description", "creator", "homepageURL"];
  7498.  
  7499.     for (var i = 0; i < singleProps.length; ++i) {
  7500.       var property = EM_R(singleProps[i]);
  7501.       var literal = installManifest.GetTarget(sourceRes, property, true);
  7502.       // If literal is null, _setProperty will remove any existing.
  7503.       this._setProperty(this._inner, targetRes, property, literal);
  7504.     }
  7505.  
  7506.     // Assert properties with multiple values
  7507.     var manyProps = ["developer", "translator", "contributor"];
  7508.     for (var i = 0; i < manyProps.length; ++i) {
  7509.       var property = EM_R(manyProps[i]);
  7510.       var literals = installManifest.GetTargets(sourceRes, property, true);
  7511.  
  7512.       var oldValues = this._inner.GetTargets(targetRes, property, true);
  7513.       while (oldValues.hasMoreElements()) {
  7514.         var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7515.         this._inner.Unassert(targetRes, property, oldValue);
  7516.       }
  7517.       while (literals.hasMoreElements()) {
  7518.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7519.         this._inner.Assert(targetRes, property, literal, true);
  7520.       }
  7521.     }
  7522.  
  7523.   },
  7524.  
  7525.   /**
  7526.    * Copies metadata from an Install Manifest Datasource into the Extensions
  7527.    * DataSource.
  7528.    * @param   id
  7529.    *          The GUID of the item
  7530.    * @param   installManifest
  7531.    *          The Install Manifest datasource we are copying from
  7532.    * @param   installLocation
  7533.    *          The Install Location of the item.
  7534.    */
  7535.   addItemMetadata: function(id, installManifest, installLocation) {
  7536.     var targetRes = getResourceForID(id);
  7537.     // Remove any temporary assertions used for the install process
  7538.     this._setProperty(this._inner, targetRes, EM_R("newVersion"), null);
  7539.     // Copy the assertions over from the source datasource.
  7540.     // Assert properties with single values
  7541.     var singleProps = ["version", "updateURL", "updateService", "optionsURL",
  7542.                        "aboutURL", "iconURL", "internalName", "updateKey"];
  7543.  
  7544.     // Items installed into restricted Install Locations can also be locked
  7545.     // (can't be removed or disabled), and hidden (not shown in the UI)
  7546.     if (installLocation.restricted)
  7547.       singleProps = singleProps.concat(["locked", "hidden"]);
  7548.     if (installLocation.name == KEY_APP_GLOBAL)
  7549.       singleProps = singleProps.concat(["appManaged"]);
  7550.     for (var i = 0; i < singleProps.length; ++i) {
  7551.       var property = EM_R(singleProps[i]);
  7552.       var literal = installManifest.GetTarget(gInstallManifestRoot, property, true);
  7553.       // If literal is null, _setProperty will remove any existing.
  7554.       this._setProperty(this._inner, targetRes, property, literal);
  7555.     }
  7556.  
  7557.     var localizedProp = EM_R("localized");
  7558.     var localeProp = EM_R("locale");
  7559.     // Remove old localized properties
  7560.     var oldValues = this._inner.GetTargets(targetRes, localizedProp, true);
  7561.     while (oldValues.hasMoreElements()) {
  7562.       var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7563.       this._cleanResource(oldValue);
  7564.       this._inner.Unassert(targetRes, localizedProp, oldValue);
  7565.     }
  7566.     // Add each localized property
  7567.     var localizations = installManifest.GetTargets(gInstallManifestRoot, localizedProp, true);
  7568.     while (localizations.hasMoreElements()) {
  7569.       var localization = localizations.getNext().QueryInterface(Ci.nsIRDFResource);
  7570.       var anon = gRDF.GetAnonymousResource();
  7571.       var literals = installManifest.GetTargets(localization, localeProp, true);
  7572.       while (literals.hasMoreElements()) {
  7573.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7574.         this._inner.Assert(anon, localeProp, literal, true);
  7575.       }
  7576.       this._addLocalizedMetadata(installManifest, localization, anon);
  7577.       this._inner.Assert(targetRes, localizedProp, anon, true);
  7578.     }
  7579.     // Add the fallback properties
  7580.     this._addLocalizedMetadata(installManifest, gInstallManifestRoot, targetRes);
  7581.  
  7582.     // Version/Dependency Info
  7583.     var versionProps = ["targetApplication", "requires"];
  7584.     var idRes = EM_R("id");
  7585.     var minVersionRes = EM_R("minVersion");
  7586.     var maxVersionRes = EM_R("maxVersion");
  7587.     for (var i = 0; i < versionProps.length; ++i) {
  7588.       var property = EM_R(versionProps[i]);
  7589.       var newVersionInfos = installManifest.GetTargets(gInstallManifestRoot, property, true);
  7590.  
  7591.       var oldVersionInfos = this._inner.GetTargets(targetRes, property, true);
  7592.       while (oldVersionInfos.hasMoreElements()) {
  7593.         var oldVersionInfo = oldVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7594.         this._cleanResource(oldVersionInfo);
  7595.         this._inner.Unassert(targetRes, property, oldVersionInfo);
  7596.       }
  7597.       while (newVersionInfos.hasMoreElements()) {
  7598.         var newVersionInfo = newVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7599.         var anon = gRDF.GetAnonymousResource();
  7600.         this._inner.Assert(anon, idRes, installManifest.GetTarget(newVersionInfo, idRes, true), true);
  7601.         this._inner.Assert(anon, minVersionRes, installManifest.GetTarget(newVersionInfo, minVersionRes, true), true);
  7602.         this._inner.Assert(anon, maxVersionRes, installManifest.GetTarget(newVersionInfo, maxVersionRes, true), true);
  7603.         this._inner.Assert(targetRes, property, anon, true);
  7604.       }
  7605.     }
  7606.     this.updateProperty(id, "opType");
  7607.     this.updateProperty(id, "updateable");
  7608.     this.Flush();
  7609.   },
  7610.  
  7611.   /**
  7612.    * Strips an item entry of all assertions.
  7613.    * @param   id
  7614.    *          The GUID of the item
  7615.    */
  7616.   removeItemMetadata: function(id) {
  7617.     var item = getResourceForID(id);
  7618.     var resources = ["targetApplication", "requires", "localized"];
  7619.     for (var i = 0; i < resources.length; ++i) {
  7620.       var targetApps = this._inner.GetTargets(item, EM_R(resources[i]), true);
  7621.       while (targetApps.hasMoreElements()) {
  7622.         var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  7623.         this._cleanResource(targetApp);
  7624.       }
  7625.     }
  7626.  
  7627.     this._cleanResource(item);
  7628.   },
  7629.  
  7630.   /**
  7631.    * Strips a resource of all outbound assertions. We use methods like this
  7632.    * since the RDFXMLDatasource will write out all assertions, even if they
  7633.    * are not connected through our root.
  7634.    * @param   resource
  7635.    *          The resource to clean.
  7636.    */
  7637.   _cleanResource: function(resource) {
  7638.     // Remove outward arcs
  7639.     var arcs = this._inner.ArcLabelsOut(resource);
  7640.     while (arcs.hasMoreElements()) {
  7641.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  7642.       var targets = this._inner.GetTargets(resource, arc, true);
  7643.       while (targets.hasMoreElements()) {
  7644.         var value = targets.getNext().QueryInterface(Ci.nsIRDFNode);
  7645.         if (value)
  7646.           this._inner.Unassert(resource, arc, value);
  7647.       }
  7648.     }
  7649.   },
  7650.  
  7651.   /**
  7652.    * Notify views that this propery has changed (this is for properties that
  7653.    * are implemented by this datasource rather than by the inner in-memory
  7654.    * datasource and thus do not get free change handling).
  7655.    * @param   id
  7656.    *          The GUID of the item to update the property for.
  7657.    * @param   property
  7658.    *          The property (less EM_NS) to update.
  7659.    */
  7660.   updateProperty: function(id, property) {
  7661.     var item = getResourceForID(id);
  7662.     this._updateProperty(item, property);
  7663.   },
  7664.  
  7665.   /**
  7666.    * Notify views that this propery has changed (this is for properties that
  7667.    * are implemented by this datasource rather than by the inner in-memory
  7668.    * datasource and thus do not get free change handling). This allows updating
  7669.    * properties for download items which don't have the em item prefix in there
  7670.    ( resource value. In most instances updateProperty should be used.
  7671.    * @param   item
  7672.    *          The item to update the property for.
  7673.    * @param   property
  7674.    *          The property (less EM_NS) to update.
  7675.    */
  7676.   _updateProperty: function(item, property) {
  7677.     if (item) {
  7678.       var propertyResource = EM_R(property);
  7679.       var value = this.GetTarget(item, propertyResource, true);
  7680.       for (var i = 0; i < this._observers.length; ++i) {
  7681.         if (value)
  7682.           this._observers[i].onChange(this, item, propertyResource,
  7683.                                       EM_L(""), value);
  7684.         else
  7685.           this._observers[i].onUnassert(this, item, propertyResource,
  7686.                                         EM_L(""));
  7687.       }
  7688.     }
  7689.   },
  7690.  
  7691.   /**
  7692.    * Move an Item to the index of another item in its container.
  7693.    * @param   movingID
  7694.    *          The ID of the item to be moved.
  7695.    * @param   destinationID
  7696.    *          The ID of an item to move another item to.
  7697.    */
  7698.   moveToIndexOf: function(movingID, destinationID) {
  7699.     var extensions = gRDF.GetResource(RDFURI_ITEM_ROOT);
  7700.     var ctr = getContainer(this._inner, extensions);
  7701.     var item = gRDF.GetResource(movingID);
  7702.     var index = ctr.IndexOf(gRDF.GetResource(destinationID));
  7703.     if (index == -1)
  7704.       index = 1; // move to the beginning if destinationID is not found
  7705.     this._inner.beginUpdateBatch();
  7706.     ctr.RemoveElement(item, true);
  7707.     ctr.InsertElementAt(item, index, true);
  7708.     this._inner.endUpdateBatch();
  7709.     this.Flush();
  7710.   },
  7711.  
  7712.   /**
  7713.    * Sorts addons of the specified type by the specified property starting from
  7714.    * the top of their container. If the addons are already sorted then no action
  7715.    * is performed.
  7716.    * @param   type
  7717.    *          The nsIUpdateItem type of the items to sort.
  7718.    * @param   propertyName
  7719.    *          The RDF property name used for sorting.
  7720.    * @param   isAscending
  7721.    *          true to sort ascending and false to sort descending
  7722.    */
  7723.   sortTypeByProperty: function(type, propertyName, isAscending) {
  7724.     var items = [];
  7725.     var ctr = getContainer(this._inner, this._itemRoot);
  7726.     var elements = ctr.GetElements();
  7727.     // Base 0 ordinal for checking against the existing order after sorting
  7728.     var ordinal = 0;
  7729.     while (elements.hasMoreElements()) {
  7730.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7731.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7732.       var itemType = this.getItemProperty(id, "type");
  7733.       if (itemType & type) {
  7734.         items.push({ item   : item,
  7735.                      ordinal: ordinal,
  7736.                      sortkey: this.getItemProperty(id, propertyName).toLowerCase() });
  7737.         ordinal++;
  7738.       }
  7739.     }
  7740.  
  7741.     var direction = isAscending ? 1 : -1;
  7742.     // Case insensitive sort
  7743.     function compare(a, b) {
  7744.         if (a.sortkey < b.sortkey) return (-1 * direction);
  7745.         if (a.sortkey > b.sortkey) return (1 * direction);
  7746.         return 0;
  7747.     }
  7748.     items.sort(compare);
  7749.  
  7750.     // Check if there are any changes in the order of the items
  7751.     var isDirty = false;
  7752.     for (var i = 0; i < items.length; i++) {
  7753.       if (items[i].ordinal != i) {
  7754.         isDirty = true;
  7755.         break;
  7756.       }
  7757.     }
  7758.  
  7759.     // If there are no changes then early return to avoid the perf impact
  7760.     if (!isDirty)
  7761.       return;
  7762.  
  7763.     // Reorder the items by moving them to the top of the container
  7764.     this.beginUpdateBatch();
  7765.     for (i = 0; i < items.length; i++) {
  7766.       ctr.RemoveElement(items[i].item, true);
  7767.       ctr.InsertElementAt(items[i].item, i + 1, true);
  7768.     }
  7769.     this.endUpdateBatch();
  7770.     this.Flush();
  7771.   },
  7772.  
  7773.   /**
  7774.    * Determines if an Item is an active download
  7775.    * @param   id
  7776.    *          The ID of the item. This will be a uri scheme without the
  7777.    *          em item prefix so getProperty shouldn't be used.
  7778.    * @returns true if the item is an active download, false otherwise.
  7779.    */
  7780.   isDownloadItem: function(id) {
  7781.     var downloadURL = stringData(this.GetTarget(gRDF.GetResource(id), EM_R("downloadURL"), true));
  7782.     return downloadURL && downloadURL != "";
  7783.   },
  7784.  
  7785.   /**
  7786.    * Adds an entry representing an active download to the appropriate container
  7787.    * @param   addon
  7788.    *          An object implementing nsIUpdateItem for the addon being
  7789.    *          downloaded.
  7790.    */
  7791.   addDownload: function(addon) {
  7792.     // Updates have already been added to the datasource so we just update the
  7793.     // download state.
  7794.     if (addon.id != addon.xpiURL) {
  7795.       this.updateDownloadState(PREFIX_ITEM_URI + addon.id, "waiting");
  7796.       return;
  7797.     }
  7798.     var res = gRDF.GetResource(addon.xpiURL);
  7799.     this._setProperty(this._inner, res, EM_R("name"), EM_L(addon.name));
  7800.     this._setProperty(this._inner, res, EM_R("version"), EM_L(addon.version));
  7801.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(addon.iconURL));
  7802.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(addon.xpiURL));
  7803.     this._setProperty(this._inner, res, EM_R("type"), EM_I(addon.type));
  7804.  
  7805.     var ctr = getContainer(this._inner, this._itemRoot);
  7806.     if (ctr.IndexOf(res) == -1)
  7807.       ctr.AppendElement(res);
  7808.  
  7809.     this.updateDownloadState(addon.xpiURL, "waiting");
  7810.     this.Flush();
  7811.   },
  7812.  
  7813.   /**
  7814.    * Adds an entry representing an item that is incompatible and is being
  7815.    * checked for a compatibility update.
  7816.    * @param   name
  7817.    *          The display name of the item being checked
  7818.    * @param   url
  7819.    *          The URL string of the xpi file that has been staged.
  7820.    * @param   type
  7821.    *          The nsIUpdateItem type of the item
  7822.    * @param   version
  7823.    *          The version of the item
  7824.    */
  7825.   addIncompatibleUpdateItem: function(name, url, type, version) {
  7826.     var iconURL = (type == Ci.nsIUpdateItem.TYPE_THEME) ? URI_GENERIC_ICON_THEME :
  7827.                                                           URI_GENERIC_ICON_XPINSTALL;
  7828.     var extensionsStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  7829.     var updateMsg = extensionsStrings.formatStringFromName("incompatibleUpdateMessage",
  7830.                                                            [BundleManager.appName, name], 2)
  7831.  
  7832.     var res = gRDF.GetResource(url);
  7833.     this._setProperty(this._inner, res, EM_R("name"), EM_L(name));
  7834.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(iconURL));
  7835.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(url));
  7836.     this._setProperty(this._inner, res, EM_R("type"), EM_I(type));
  7837.     this._setProperty(this._inner, res, EM_R("version"), EM_L(version));
  7838.     this._setProperty(this._inner, res, EM_R("incompatibleUpdate"), EM_L("true"));
  7839.     this._setProperty(this._inner, res, EM_R("description"), EM_L(updateMsg));
  7840.  
  7841.     var ctr = getContainer(this._inner, this._itemRoot);
  7842.     if (ctr.IndexOf(res) == -1)
  7843.       ctr.AppendElement(res);
  7844.  
  7845.     this.updateDownloadState(url, "incompatibleUpdate");
  7846.     this.Flush();
  7847.   },
  7848.  
  7849.   /**
  7850.    * Removes an active download from the appropriate container
  7851.    * @param   url
  7852.    *          The URL string of the active download to be removed
  7853.    */
  7854.   removeDownload: function(url) {
  7855.     var res = gRDF.GetResource(url);
  7856.     var ctr = getContainer(this._inner, this._itemRoot);
  7857.     if (ctr.IndexOf(res) != -1)
  7858.       ctr.RemoveElement(res, true);
  7859.     this._cleanResource(res);
  7860.     this.updateDownloadState(url, null);
  7861.     this.Flush();
  7862.   },
  7863.  
  7864.   /**
  7865.    * A hash of RDF resource values (e.g. Add-on IDs or XPI URLs) that represent
  7866.    * installation progress for a single browser session.
  7867.    */
  7868.   _progressData: { },
  7869.  
  7870.   /**
  7871.    * Updates the install progress data for a given ID (e.g. Add-on IDs or
  7872.    * XPI URLs).
  7873.    * @param   id
  7874.    *          The URL string of the active download to be removed
  7875.    * @param   state
  7876.    *          The current state in the installation process. If null the object
  7877.    *          is deleted from _progressData.
  7878.    */
  7879.   updateDownloadState: function(id, state) {
  7880.     if (!state) {
  7881.       if (id in this._progressData)
  7882.         delete this._progressData[id];
  7883.       return;
  7884.     }
  7885.     else {
  7886.       if (!(id in this._progressData))
  7887.         this._progressData[id] = { };
  7888.       this._progressData[id].state = state;
  7889.     }
  7890.     var item = gRDF.GetResource(id);
  7891.     this._updateProperty(item, "state");
  7892.   },
  7893.  
  7894.   updateDownloadProgress: function(id, progress) {
  7895.     if (!progress) {
  7896.       if (!(id in this._progressData))
  7897.         return;
  7898.       this._progressData[id].progress = null;
  7899.     }
  7900.     else {
  7901.       if (!(id in this._progressData))
  7902.         this.updateDownloadState(id, "downloading");
  7903.  
  7904.       if (this._progressData[id].progress == progress)
  7905.         return;
  7906.  
  7907.       this._progressData[id].progress = progress;
  7908.     }
  7909.     var item = gRDF.GetResource(id);
  7910.     this._updateProperty(item, "progress");
  7911.   },
  7912.  
  7913.   /**
  7914.    * A GUID->location-key hash of items that are visible to the application.
  7915.    * These are items that show up in the Extension/Themes etc UI. If there is
  7916.    * an instance of the same item installed in Install Locations of differing
  7917.    * profiles, the item at the highest priority location will appear in this
  7918.    * list.
  7919.    */
  7920.   visibleItems: { },
  7921.  
  7922.   /**
  7923.    * Walk the list of installed items and determine what the visible list is,
  7924.    * based on which items are visible at the highest priority locations.
  7925.    */
  7926.   _buildVisibleItemList: function() {
  7927.     var ctr = getContainer(this, this._itemRoot);
  7928.     var items = ctr.GetElements();
  7929.     while (items.hasMoreElements()) {
  7930.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  7931.       // Resource URIs adopt the format: location-key,item-id
  7932.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7933.       this.visibleItems[id] = this.getItemProperty(id, "installLocation");
  7934.     }
  7935.   },
  7936.  
  7937.   /**
  7938.    * Updates an item's location in the visible item list.
  7939.    * @param   id
  7940.    *          The GUID of the item to update
  7941.    * @param   locationKey
  7942.    *          The name of the Install Location where the item is installed.
  7943.    * @param   forceReplace
  7944.    *          true if the new location should be used, regardless of its
  7945.    *          priority relationship to existing entries, false if the location
  7946.    *          should only be updated if its priority is lower than the existing
  7947.    *          value.
  7948.    */
  7949.   updateVisibleList: function(id, locationKey, forceReplace) {
  7950.     if (id in this.visibleItems && this.visibleItems[id]) {
  7951.       var oldLocation = InstallLocations.get(this.visibleItems[id]);
  7952.       var newLocation = InstallLocations.get(locationKey);
  7953.       if (forceReplace || !oldLocation || newLocation.priority < oldLocation.priority)
  7954.         this.visibleItems[id] = locationKey;
  7955.     }
  7956.     else
  7957.       this.visibleItems[id] = locationKey;
  7958.   },
  7959.  
  7960.   /**
  7961.    * Load the Extensions Datasource from disk.
  7962.    */
  7963.   loadExtensions: function() {
  7964.     var extensionsFile  = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  7965.     try {
  7966.       this._inner = gRDF.GetDataSourceBlocking(getURLSpecFromFile(extensionsFile));
  7967.     }
  7968.     catch (e) {
  7969.       ERROR("Datasource::loadExtensions: removing corrupted extensions datasource " +
  7970.             " file = " + extensionsFile.path + ", exception = " + e + "\n");
  7971.       extensionsFile.remove(false);
  7972.       return;
  7973.     }
  7974.  
  7975.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  7976.              getService(Ci.nsIRDFContainerUtils);
  7977.     cu.MakeSeq(this._inner, this._itemRoot);
  7978.  
  7979.     this._buildVisibleItemList();
  7980.   },
  7981.  
  7982.   /**
  7983.    * See nsIExtensionManager.idl
  7984.    */
  7985.   onUpdateStarted: function() {
  7986.     LOG("Datasource: Update Started");
  7987.   },
  7988.  
  7989.   /**
  7990.    * See nsIExtensionManager.idl
  7991.    */
  7992.   onUpdateEnded: function() {
  7993.     LOG("Datasource: Update Ended");
  7994.   },
  7995.  
  7996.   /**
  7997.    * See nsIExtensionManager.idl
  7998.    */
  7999.   onAddonUpdateStarted: function(addon) {
  8000.     if (!addon)
  8001.       throw Cr.NS_ERROR_INVALID_ARG;
  8002.  
  8003.     LOG("Datasource: Addon Update Started: " + addon.id);
  8004.     this.updateProperty(addon.id, "availableUpdateURL");
  8005.   },
  8006.  
  8007.   /**
  8008.    * See nsIExtensionManager.idl
  8009.    */
  8010.   onAddonUpdateEnded: function(addon, status) {
  8011.     if (!addon)
  8012.       throw Cr.NS_ERROR_INVALID_ARG;
  8013.  
  8014.     LOG("Datasource: Addon Update Ended: " + addon.id + ", status: " + status);
  8015.     var url = null, hash = null, version = null;
  8016.     var updateAvailable = status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  8017.     if (updateAvailable) {
  8018.       url = EM_L(addon.xpiURL);
  8019.       if (addon.xpiHash)
  8020.         hash = EM_L(addon.xpiHash);
  8021.       version = EM_L(addon.version);
  8022.     }
  8023.     this.setItemProperties(addon.id, {
  8024.       availableUpdateURL: url,
  8025.       availableUpdateHash: hash,
  8026.       availableUpdateVersion: version
  8027.     });
  8028.     this.updateProperty(addon.id, "availableUpdateURL");
  8029.   },
  8030.  
  8031.   /////////////////////////////////////////////////////////////////////////////
  8032.   // nsIRDFDataSource
  8033.   get URI() {
  8034.     return "rdf:extensions";
  8035.   },
  8036.  
  8037.   GetSource: function(property, target, truthValue) {
  8038.     return this._inner.GetSource(property, target, truthValue);
  8039.   },
  8040.  
  8041.   GetSources: function(property, target, truthValue) {
  8042.     return this._inner.GetSources(property, target, truthValue);
  8043.   },
  8044.  
  8045.   /**
  8046.    * Gets an URL to a theme's image file
  8047.    * @param   item
  8048.    *          The RDF Resource representing the item
  8049.    * @param   fileName
  8050.    *          The file to locate a URL for
  8051.    * @param   fallbackURL
  8052.    *          If the location fails, supply this URL instead
  8053.    * @returns An RDF Resource to the URL discovered, or the fallback
  8054.    *          if the discovery failed.
  8055.    */
  8056.   _getThemeImageURL: function(item, fileName, fallbackURL) {
  8057.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8058.     var installLocation = this._em.getInstallLocation(id);
  8059.     if (!installLocation)
  8060.       return fallbackURL;
  8061.     var file = installLocation.getItemFile(id, fileName)
  8062.     if (file.exists())
  8063.       return gRDF.GetResource(getURLSpecFromFile(file));
  8064.  
  8065.     if (id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)) {
  8066.       var jarFile = getFile(KEY_APPDIR, [DIR_CHROME, FILE_DEFAULT_THEME_JAR]);
  8067.       var url = "jar:" + getURLSpecFromFile(jarFile) + "!/" + fileName;
  8068.       return gRDF.GetResource(url);
  8069.     }
  8070.  
  8071.     return fallbackURL ? gRDF.GetResource(fallbackURL) : null;
  8072.   },
  8073.  
  8074.   /**
  8075.    * Get the em:iconURL property (icon url of the item)
  8076.    */
  8077.   _rdfGet_iconURL: function(item, property) {
  8078.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8079.     var type = this.getItemProperty(id, "type");
  8080.     if (type & Ci.nsIUpdateItem.TYPE_THEME)
  8081.       return this._getThemeImageURL(item, "icon.png", URI_GENERIC_ICON_THEME);
  8082.  
  8083.     if (inSafeMode())
  8084.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8085.  
  8086.     var hasIconURL = this._inner.hasArcOut(item, property);
  8087.     // If the addon doesn't have an IconURL property or it is disabled use the
  8088.     // generic icon URL instead.
  8089.     if (!hasIconURL || this.getItemProperty(id, "isDisabled") == "true")
  8090.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8091.     var iconURL = stringData(this._inner.GetTarget(item, property, true));
  8092.     try {
  8093.       var uri = newURI(iconURL);
  8094.       var scheme = uri.scheme;
  8095.       // Only allow chrome URIs or when installing http(s) URIs.
  8096.       if (scheme == "chrome" || (scheme == "http" || scheme == "https") &&
  8097.           this._inner.hasArcOut(item, EM_R("downloadURL")))
  8098.         return null;
  8099.     }
  8100.     catch (e) {
  8101.     }
  8102.     // Use a generic icon URL for addons that have an invalid iconURL.
  8103.     return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8104.   },
  8105.  
  8106.   /**
  8107.    * Get the em:previewImage property (preview image of the item)
  8108.    */
  8109.   _rdfGet_previewImage: function(item, property) {
  8110.     var type = this.getItemProperty(stripPrefix(item.Value, PREFIX_ITEM_URI), "type");
  8111.     if (type != -1 && type & Ci.nsIUpdateItem.TYPE_THEME)
  8112.       return this._getThemeImageURL(item, "preview.png", null);
  8113.     return null;
  8114.   },
  8115.  
  8116.   /**
  8117.    * If we're in safe mode, the item is disabled by the user or app, or the
  8118.    * item is to be upgraded force the generic about dialog for the item.
  8119.    */
  8120.   _rdfGet_aboutURL: function(item, property) {
  8121.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8122.     if (inSafeMode() || this.getItemProperty(id, "isDisabled") == "true" ||
  8123.         this.getItemProperty(id, "opType") == OP_NEEDS_UPGRADE)
  8124.       return EM_L("");
  8125.  
  8126.     return null;
  8127.   },
  8128.  
  8129.   _rdfGet_installDate: function(item, property) {
  8130.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8131.     var key = this.getItemProperty(id, "installLocation");
  8132.     if (key && key in StartupCache.entries && id in StartupCache.entries[key] &&
  8133.         StartupCache.entries[key][id] && StartupCache.entries[key][id].mtime)
  8134.       return EM_D(StartupCache.entries[key][id].mtime * 1000000);
  8135.     return null;
  8136.   },
  8137.  
  8138.   /**
  8139.    * Get the em:compatible property (whether or not this item is compatible)
  8140.    */
  8141.   _rdfGet_compatible: function(item, property) {
  8142.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8143.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  8144.     if (!targetAppInfo) {
  8145.       // When installing a new addon targetAppInfo does not exist yet
  8146.       if (this.getItemProperty(id, "opType") == OP_NEEDS_INSTALL)
  8147.         return EM_L("true");
  8148.       return EM_L("false");
  8149.     }
  8150.  
  8151.     getVersionChecker();
  8152.     var appVersion = targetAppInfo.appID == TOOLKIT_ID ? gApp.platformVersion : gApp.version;
  8153.     if (gVersionChecker.compare(targetAppInfo.maxVersion, appVersion) < 0 ||
  8154.         gVersionChecker.compare(appVersion, targetAppInfo.minVersion) < 0) {
  8155.       // OK, this item is incompatible.
  8156.       return EM_L("false");
  8157.     }
  8158.     return EM_L("true");
  8159.   },
  8160.  
  8161.   /**
  8162.    * Get the providesUpdatesSecurely property (whether or not this item has a
  8163.    * secure update mechanism)
  8164.    */
  8165.   _rdfGet_providesUpdatesSecurely: function(item, property) {
  8166.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8167.     if (this.getItemProperty(id, "updateKey") ||
  8168.         !this.getItemProperty(id, "updateURL") ||
  8169.         this.getItemProperty(id, "updateURL").substring(0, 6) == "https:")
  8170.       return EM_L("true");
  8171.     return EM_L("false");
  8172.   },
  8173.  
  8174.   /**
  8175.    * Get the em:blocklisted property (whether or not this item is blocklisted)
  8176.    */
  8177.   _rdfGet_blocklisted: function(item, property) {
  8178.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8179.     var version = this.getItemProperty(id, "version");
  8180.     if (!gBlocklist)
  8181.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  8182.                    getService(Ci.nsIBlocklistService);
  8183.     if (gBlocklist.isAddonBlocklisted(id, version, null, null))
  8184.       return EM_L("true");
  8185.  
  8186.     return EM_L("false");
  8187.   },
  8188.  
  8189.   /**
  8190.    * Get the em:state property (represents the current phase of an install).
  8191.    */
  8192.   _rdfGet_state: function(item, property) {
  8193.     var id = item.Value;
  8194.     if (id in this._progressData)
  8195.       return EM_L(this._progressData[id].state);
  8196.     return null;
  8197.   },
  8198.  
  8199.   /**
  8200.    * Get the em:progress property from the _progressData js object. By storing
  8201.    * progress which is updated repeastedly during a download we avoid
  8202.    * repeastedly writing it to the rdf file.
  8203.    */
  8204.   _rdfGet_progress: function(item, property) {
  8205.     var id = item.Value;
  8206.     if (id in this._progressData)
  8207.       return EM_I(this._progressData[id].progress);
  8208.     return null;
  8209.   },
  8210.  
  8211.   /**
  8212.    * Get the em:appManaged property. This prevents extensions from hiding
  8213.    * extensions installed into locations other than the app-global location.
  8214.    */
  8215.   _rdfGet_appManaged: function(item, property) {
  8216.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8217.     var locationKey = this.getItemProperty(id, "installLocation");
  8218.     if (locationKey != KEY_APP_GLOBAL)
  8219.       return EM_L("false");
  8220.     return null;
  8221.   },
  8222.  
  8223.   /**
  8224.    * Get the em:hidden property. This prevents extensions from hiding
  8225.    * extensions installed into locations other than restricted locations.
  8226.    */
  8227.   _rdfGet_hidden: function(item, property) {
  8228.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8229.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8230.     if (!installLocation || !installLocation.restricted)
  8231.       return EM_L("false");
  8232.     return null;
  8233.   },
  8234.  
  8235.   /**
  8236.    * Get the em:locked property. This prevents extensions from locking
  8237.    * extensions installed into locations other than restricted locations.
  8238.    */
  8239.   _rdfGet_locked: function(item, property) {
  8240.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8241.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8242.     if (!installLocation || !installLocation.restricted)
  8243.       return EM_L("false");
  8244.     return null;
  8245.   },
  8246.  
  8247.   /**
  8248.    * Get the em:satisfiesDependencies property - literal string "false" for
  8249.    * dependencies not satisfied (e.g. dependency disabled, incorrect version,
  8250.    * not installed etc.), and literal string "true" for dependencies satisfied.
  8251.    */
  8252.   _rdfGet_satisfiesDependencies: function(item, property) {
  8253.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8254.     if (this.satisfiesDependencies(id))
  8255.       return EM_L("true");
  8256.     return EM_L("false");
  8257.   },
  8258.  
  8259.   /**
  8260.    * Get the em:opType property (controls widget state for the EM UI)
  8261.    * from the Startup Cache (e.g. extensions.cache)
  8262.    */
  8263.   _rdfGet_opType: function(item, property) {
  8264.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8265.     var key = this.getItemProperty(id, "installLocation");
  8266.     if (key in StartupCache.entries && id in StartupCache.entries[key] &&
  8267.         StartupCache.entries[key][id] && StartupCache.entries[key][id].op != OP_NONE)
  8268.       return EM_L(StartupCache.entries[key][id].op);
  8269.     return null;
  8270.   },
  8271.  
  8272.   /**
  8273.    * Gets a localizable property. Install Manifests are generally only in one
  8274.    * language, however an item can customize by providing localized prefs in
  8275.    * the form:
  8276.    *
  8277.    *    extensions.{GUID}.[name|description|creator|homepageURL]
  8278.    *
  8279.    * to specify localized text for each of these properties.
  8280.    */
  8281.   _getLocalizablePropertyValue: function(item, property) {
  8282.     // These are localizable properties that a language pack supplied by the
  8283.     // Extension may override.
  8284.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8285.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8286.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8287.     try {
  8288.       var value = gPref.getComplexValue(prefName,
  8289.                                         Ci.nsIPrefLocalizedString);
  8290.       if (value.data)
  8291.         return EM_L(value.data);
  8292.     }
  8293.     catch (e) {
  8294.     }
  8295.  
  8296.     var localized = findClosestLocalizedResource(this._inner, item);
  8297.     if (localized) {
  8298.       var value = this._inner.GetTarget(localized, property, true);
  8299.       return value ? value : EM_L("");
  8300.     }
  8301.     return null;
  8302.   },
  8303.  
  8304.   /**
  8305.    * Get the em:name property (name of the item)
  8306.    */
  8307.   _rdfGet_name: function(item, property) {
  8308.     return this._getLocalizablePropertyValue(item, property);
  8309.   },
  8310.  
  8311.   /**
  8312.    * Get the em:description property (description of the item)
  8313.    */
  8314.   _rdfGet_description: function(item, property) {
  8315.     return this._getLocalizablePropertyValue(item, property);
  8316.   },
  8317.  
  8318.   /**
  8319.    * Get the em:creator property (creator of the item)
  8320.    */
  8321.   _rdfGet_creator: function(item, property) {
  8322.     return this._getLocalizablePropertyValue(item, property);
  8323.   },
  8324.  
  8325.   /**
  8326.    * Get the em:homepageURL property (homepage URL of the item)
  8327.    */
  8328.   _rdfGet_homepageURL: function(item, property) {
  8329.     return this._getLocalizablePropertyValue(item, property);
  8330.   },
  8331.   
  8332.   _rdfGet_availableUpdateInfo: function(item, property) {
  8333.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8334.     var uri = stringData(this._inner.GetTarget(item, EM_R("availableUpdateInfo"), true));
  8335.     if (uri) {
  8336.       uri = escapeAddonURI(this.getItemForID(id), uri, this);
  8337.       return EM_L(uri);
  8338.     }
  8339.     return null;
  8340.   },
  8341.  
  8342.   /**
  8343.    * Get the em:isDisabled property. This will be true if the item has a
  8344.    * appDisabled or a userDisabled property that is true or OP_NEEDS_ENABLE.
  8345.    */
  8346.   _rdfGet_isDisabled: function(item, property) {
  8347.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8348.     if (this.getItemProperty(id, "userDisabled") == "true" ||
  8349.         this.getItemProperty(id, "appDisabled") == "true" ||
  8350.         this.getItemProperty(id, "userDisabled") == OP_NEEDS_ENABLE ||
  8351.         this.getItemProperty(id, "appDisabled") == OP_NEEDS_ENABLE)
  8352.       return EM_L("true");
  8353.     return EM_L("false");
  8354.   },
  8355.  
  8356.   _rdfGet_addonID: function(item, property) {
  8357.     var id = this._inner.GetTarget(item, EM_R("downloadURL"), true) ? item.Value :
  8358.                                                                       stripPrefix(item.Value, PREFIX_ITEM_URI);
  8359.     return EM_L(id);
  8360.   },
  8361.  
  8362.   /**
  8363.    * Get the em:updateable property - this specifies whether the item is
  8364.    * allowed to be updated
  8365.    */
  8366.   _rdfGet_updateable: function(item, property) {
  8367.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8368.     var opType = this.getItemProperty(id, "opType");
  8369.     if (opType != OP_NONE || this.getItemProperty(id, "appManaged") == "true")
  8370.       return EM_L("false");
  8371.  
  8372.     if (getPref("getBoolPref", (PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, id), false)) == true)
  8373.       return EM_L("false");
  8374.  
  8375.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8376.     if (!installLocation || !installLocation.canAccess)
  8377.       return EM_L("false");
  8378.  
  8379.     return EM_L("true");
  8380.   },
  8381.  
  8382.   /**
  8383.    * See nsIRDFDataSource.idl
  8384.    */
  8385.   GetTarget: function(source, property, truthValue) {
  8386.     if (!source)
  8387.       return null;
  8388.  
  8389.     var target = null;
  8390.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8391.     if (getter in this)
  8392.       target = this[getter](source, property);
  8393.  
  8394.     return target || this._inner.GetTarget(source, property, truthValue);
  8395.   },
  8396.  
  8397.   /**
  8398.    * Gets an enumeration of values of a localizable property. Install Manifests
  8399.    * are generally only in one language, however an item can customize by
  8400.    * providing localized prefs in the form:
  8401.    *
  8402.    *    extensions.{GUID}.[contributor].1
  8403.    *    extensions.{GUID}.[contributor].2
  8404.    *    extensions.{GUID}.[contributor].3
  8405.    *    ...
  8406.    *
  8407.    * to specify localized text for each of these properties.
  8408.    */
  8409.   _getLocalizablePropertyValues: function(item, property) {
  8410.     // These are localizable properties that a language pack supplied by the
  8411.     // Extension may override.
  8412.     var values = [];
  8413.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8414.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8415.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8416.     var i = 0;
  8417.     while (true) {
  8418.       try {
  8419.         var value = gPref.getComplexValue(prefName + "." + ++i,
  8420.                                           Ci.nsIPrefLocalizedString);
  8421.         if (value.data)
  8422.           values.push(EM_L(value.data));
  8423.       }
  8424.       catch (e) {
  8425.         try {
  8426.           var value = gPref.getComplexValue(prefName,
  8427.                                             Ci.nsIPrefLocalizedString);
  8428.           if (value.data)
  8429.             values.push(EM_L(value.data));
  8430.         }
  8431.         catch (e) {
  8432.         }
  8433.         break;
  8434.       }
  8435.     }
  8436.     if (values.length > 0)
  8437.       return values;
  8438.  
  8439.     var localized = findClosestLocalizedResource(this._inner, item);
  8440.     if (localized) {
  8441.       var targets = this._inner.GetTargets(localized, property, true);
  8442.       while (targets.hasMoreElements())
  8443.         values.push(targets.getNext());
  8444.       return values;
  8445.     }
  8446.     return null;
  8447.   },
  8448.  
  8449.   /**
  8450.    * Get the em:developer property (developers of the extension)
  8451.    */
  8452.   _rdfGets_developer: function(item, property) {
  8453.     return this._getLocalizablePropertyValues(item, property);
  8454.   },
  8455.  
  8456.   /**
  8457.    * Get the em:translator property (translators of the extension)
  8458.    */
  8459.   _rdfGets_translator: function(item, property) {
  8460.     return this._getLocalizablePropertyValues(item, property);
  8461.   },
  8462.  
  8463.   /**
  8464.    * Get the em:contributor property (contributors to the extension)
  8465.    */
  8466.   _rdfGets_contributor: function(item, property) {
  8467.     return this._getLocalizablePropertyValues(item, property);
  8468.   },
  8469.  
  8470.   /**
  8471.    * See nsIRDFDataSource.idl
  8472.    */
  8473.   GetTargets: function(source, property, truthValue) {
  8474.     if (!source)
  8475.       return null;
  8476.  
  8477.     var ary = null;
  8478.     var propertyName = stripPrefix(property.Value, PREFIX_NS_EM);
  8479.     var getter = "_rdfGets_" + propertyName;
  8480.     if (getter in this)
  8481.       ary = this[getter](source, property);
  8482.     else {
  8483.       // The template builder calls GetTargets when single value properties
  8484.       // are used in a triple.
  8485.       getter = "_rdfGet_" + propertyName;
  8486.       if (getter in this)
  8487.         ary = [ this[getter](source, property) ];
  8488.     }
  8489.  
  8490.     return ary ? new ArrayEnumerator(ary)
  8491.                : this._inner.GetTargets(source, property, truthValue);
  8492.   },
  8493.  
  8494.   Assert: function(source, property, target, truthValue) {
  8495.     this._inner.Assert(source, property, target, truthValue);
  8496.   },
  8497.  
  8498.   Unassert: function(source, property, target) {
  8499.     this._inner.Unassert(source, property, target);
  8500.   },
  8501.  
  8502.   Change: function(source, property, oldTarget, newTarget) {
  8503.     this._inner.Change(source, property, oldTarget, newTarget);
  8504.   },
  8505.  
  8506.   Move: function(oldSource, newSource, property, target) {
  8507.     this._inner.Move(oldSource, newSource, property, target);
  8508.   },
  8509.  
  8510.   HasAssertion: function(source, property, target, truthValue) {
  8511.     if (!source || !property || !target)
  8512.       return false;
  8513.  
  8514.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8515.     if (getter in this)
  8516.       return this[getter](source, property) == target;
  8517.     return this._inner.HasAssertion(source, property, target, truthValue);
  8518.   },
  8519.  
  8520.   _observers: [],
  8521.   AddObserver: function(observer) {
  8522.     for (var i = 0; i < this._observers.length; ++i) {
  8523.       if (this._observers[i] == observer)
  8524.         return;
  8525.     }
  8526.     this._observers.push(observer);
  8527.     this._inner.AddObserver(observer);
  8528.   },
  8529.  
  8530.   RemoveObserver: function(observer) {
  8531.     for (var i = 0; i < this._observers.length; ++i) {
  8532.       if (this._observers[i] == observer)
  8533.         this._observers.splice(i, 1);
  8534.     }
  8535.     this._inner.RemoveObserver(observer);
  8536.   },
  8537.  
  8538.   ArcLabelsIn: function(node) {
  8539.     return this._inner.ArcLabelsIn(node);
  8540.   },
  8541.  
  8542.   ArcLabelsOut: function(source) {
  8543.     return this._inner.ArcLabelsOut(source);
  8544.   },
  8545.  
  8546.   GetAllResources: function() {
  8547.     return this._inner.GetAllResources();
  8548.   },
  8549.  
  8550.   IsCommandEnabled: function(sources, command, arguments) {
  8551.     return this._inner.IsCommandEnabled(sources, command, arguments);
  8552.   },
  8553.  
  8554.   DoCommand: function(sources, command, arguments) {
  8555.     this._inner.DoCommand(sources, command, arguments);
  8556.   },
  8557.  
  8558.   GetAllCmds: function(source) {
  8559.     return this._inner.GetAllCmds(source);
  8560.   },
  8561.  
  8562.   hasArcIn: function(node, arc) {
  8563.     return this._inner.hasArcIn(node, arc);
  8564.   },
  8565.  
  8566.   hasArcOut: function(source, arc) {
  8567.     return this._inner.hasArcOut(source, arc);
  8568.   },
  8569.  
  8570.   beginUpdateBatch: function() {
  8571.     return this._inner.beginUpdateBatch();
  8572.   },
  8573.  
  8574.   endUpdateBatch: function() {
  8575.     return this._inner.endUpdateBatch();
  8576.   },
  8577.  
  8578.   /**
  8579.    * See nsIRDFRemoteDataSource.idl
  8580.    */
  8581.   get loaded() {
  8582.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  8583.   },
  8584.  
  8585.   Init: function(uri) {
  8586.   },
  8587.  
  8588.   Refresh: function(blocking) {
  8589.   },
  8590.  
  8591.   Flush: function() {
  8592.     // For some operations we block repeated flushing until all operations
  8593.     // are complete to reduce file accesses that can trigger bug 431065
  8594.     if (!gAllowFlush) {
  8595.       gDSNeedsFlush = true;
  8596.       return;
  8597.     }
  8598.     if (this._inner instanceof Ci.nsIRDFRemoteDataSource)
  8599.       this._inner.Flush();
  8600.   },
  8601.  
  8602.   FlushTo: function(uri) {
  8603.   },
  8604.  
  8605.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRDFDataSource,
  8606.                                          Ci.nsIRDFRemoteDataSource])
  8607. };
  8608.  
  8609. function UpdateItem () {}
  8610. UpdateItem.prototype = {
  8611.   /**
  8612.    * See nsIUpdateService.idl
  8613.    */
  8614.   init: function(id, version, installLocationKey, minAppVersion, maxAppVersion,
  8615.                  name, downloadURL, xpiHash, iconURL, updateURL, updateKey, type,
  8616.                  targetAppID) {
  8617.     this._id                  = id;
  8618.     this._version             = version;
  8619.     this._installLocationKey  = installLocationKey;
  8620.     this._minAppVersion       = minAppVersion;
  8621.     this._maxAppVersion       = maxAppVersion;
  8622.     this._name                = name;
  8623.     this._downloadURL         = downloadURL;
  8624.     this._xpiHash             = xpiHash;
  8625.     this._iconURL             = iconURL;
  8626.     this._updateURL           = updateURL;
  8627.     this._updateKey           = updateKey;
  8628.     this._type                = type;
  8629.     this._targetAppID         = targetAppID;
  8630.   },
  8631.  
  8632.   /**
  8633.    * See nsIUpdateService.idl
  8634.    */
  8635.   get id()                { return this._id;                },
  8636.   get version()           { return this._version;           },
  8637.   get installLocationKey(){ return this._installLocationKey;},
  8638.   get minAppVersion()     { return this._minAppVersion;     },
  8639.   get maxAppVersion()     { return this._maxAppVersion;     },
  8640.   get name()              { return this._name;              },
  8641.   get xpiURL()            { return this._downloadURL;       },
  8642.   get xpiHash()           { return this._xpiHash;           },
  8643.   get iconURL()           { return this._iconURL            },
  8644.   get updateRDF()         { return this._updateURL;         },
  8645.   get updateKey()         { return this._updateKey;         },
  8646.   get type()              { return this._type;              },
  8647.   get targetAppID()       { return this._targetAppID;       },
  8648.  
  8649.   /**
  8650.    * See nsIUpdateService.idl
  8651.    */
  8652.   get objectSource() {
  8653.     return { id                 : this._id,
  8654.              version            : this._version,
  8655.              installLocationKey : this._installLocationKey,
  8656.              minAppVersion      : this._minAppVersion,
  8657.              maxAppVersion      : this._maxAppVersion,
  8658.              name               : this._name,
  8659.              xpiURL             : this._downloadURL,
  8660.              xpiHash            : this._xpiHash,
  8661.              iconURL            : this._iconURL,
  8662.              updateRDF          : this._updateURL,
  8663.              updateKey          : this._updateKey,
  8664.              type               : this._type,
  8665.              targetAppID        : this._targetAppID
  8666.            }.toSource();
  8667.   },
  8668.  
  8669.   classDescription: "Update Item",
  8670.   contractID: "@mozilla.org/updates/item;1",
  8671.   classID: Components.ID("{F3294B1C-89F4-46F8-98A0-44E1EAE92518}"),
  8672.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateItem])
  8673. };
  8674.  
  8675. var gEmSingleton = null;
  8676. var EmFactory = {
  8677.   createInstance: function(outer, iid) {
  8678.     if (outer != null)
  8679.       throw Cr.NS_ERROR_NO_AGGREGATION;
  8680.  
  8681.     if (!gEmSingleton)
  8682.       gEmSingleton = new ExtensionManager();
  8683.     return gEmSingleton.QueryInterface(iid);
  8684.   }
  8685. };
  8686.  
  8687. function DatasourceModule() {}
  8688. DatasourceModule.prototype = {
  8689.   classDescription: "Extension Manager Data Source",
  8690.   contractID: "@mozilla.org/rdf/datasource;1?name=extensions",
  8691.   classID: Components.ID("{69BB8313-2D4F-45EC-97E0-D39DA58ECCE9}"),
  8692.   _xpcom_factory: {
  8693.     createInstance: function() Cc[ExtensionManager.prototype.contractID].
  8694.                                getService(Ci.nsIExtensionManager).datasource
  8695.   }
  8696. };
  8697.  
  8698.  
  8699. function NSGetModule(compMgr, fileSpec)
  8700.   XPCOMUtils.generateModule([ExtensionManager, DatasourceModule, UpdateItem]);
  8701.  
  8702.